网络编程
位置:首页>> 网络编程>> XML编程>> 利用XMLBean轻轻松松读写XML(6)

利用XMLBean轻轻松松读写XML(6)

 来源:互联网 发布时间:2008-09-04 11:25:00 

标签:

运行,打开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。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com