推荐:浅谈XML的简易教程文档格式的排错 我妈妈_的清单中有数十条菜谱,甚至数百条。如果产生一个致命错误,排错将非常困难 - 你将一行一行地寻找丢失的标记符。如果使用几层嵌套,发现错误将很困难。但是可以找到很好
运行,打开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。
分享:解析XML轻松学习手册(3)XML的术语第三章 XML的术语提纲: 导言 一.XML文档的有关术语 二.DTD的有关术语 导言 初学XML最令人头疼的就是有一大堆新的术语概念要理解。由于XML本身也是一个崭新的技术,正在不断发展和变化,各组织