当前位置: 主页 > 编程知识 > xml编程 > 利用XMLBean轻轻松松读写XML

利用XMLBean轻轻松松读写XML

时间:2009-11-20来源:站长资讯网 点击:

运行,打开customers_new.xml:


    <?xml version="1.0" encoding="UTF-8"?>
    <Customers>
    <customer>
            <id>3</id>
            <gender>female</gender>
            <firstname>Jessica</firstname>
            <lastname>Lim</lastname>
            <phoneNumber>1234567</phoneNumber>
            <address>
                    <primaryAddress>
                         <postalCode>350106</postalCode>
                         <addressLine1>#25-1</addressLine1>
                                       <addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
                    </primaryAddress>
                    <billingAddress>
                        <receiver>Ms Danielle</receiver>
                        <postalCode>350107</postalCode>
                       <addressLine1>#167</addressLine1>
                       <addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
                    </billingAddress>
                    </address>
            </customer>
    </Customers>

七、利用XMLBean修改XML文件

我们再增加一个Method:


      public void updateCustomer(int id,String lastname) {
         try {
        File xmlFile = new File(filename);
        CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
        CustomerType[] customers = doc.getCustomers().getCustomerArray();
     
        for (int i = 0; i < customers.length; i++) {
           CustomerType customer = customers[i];
          if(customer.getId()==id){
                customer.setLastname(lastname);
                break;
            }
        }
        doc.save(xmlFile);
         } catch (Exception ex) {
          ex.printStackTrace();
         }
           }

main method:

    public static void main(String[] args) {
     String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
                   
    CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
                   
    customerXMLBean.updateCustomer(3,"last");
    }

运行之后,我们将会看到客户编号为3的客户的lastname已经改为last。

站长资讯网
.
分页: [1] [2] [3] [4] [5] [6] [7]
TAG: XML XMLBean
推荐内容最近更新人气排行
关于我们 | 友情链接 | 网址推荐 | 常用资讯 | 网站地图 | RSS | 留言