手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网络编程>Xml编程>列表

利用XMLBean轻轻松松读写XML

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

<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.

  八、利用XMLBean删除一个customer

  再增加一个Method:

public void deleteCustomer(int id) {
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.setNil() ;
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.deleteCustomer(3);
}

  运行,我们将会看到客户编号为3的客户的资料已经被删除.

  九、查询XML

  除了本文在以上讲述的,利用XMLBean能轻轻松松完成XML的读写操作外,结合XPath和XQuery,XMLBean还能完成象SQL查询数据库一样方便地查询XML数据. 关于XML查询以及如何创建XML数据库, 我将在另一篇文章里讨论.

  十、结束语

  XMLBean能帮助我们轻易读写XML,这将有助于我们降低XML的学习和使用,有了这个基础,开发人员将为学习更多地XML相关技术和Web Services,JMS等其他J2EE技术打下良好地基础.

版权声明:Techtarget获Matrix授权发布,如需转载请联系Matrix
作者:叶枫(http://blog.matrix.org.cn/page/叶枫)
原文地址:http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!