- XML code
<info> <booklist> <book> <name>Java设计模式</name> <price>150</price> </book> <book> <name>三国演义</name> <price>200</price> </book> </booklist> <picturelist> <pirture> <name>图片1</name> <price>100</price> </pirture> <pirture> <name>图片2</name> <price>200</price> </pirture> </picturelist></info>
上面是config.xml,然后我想通过java实现下面方法:
通过传进来的name和price,来更新上面的xml
比如传进来name是水浒传。price是300,那么这个xml就会变成:
- XML code
<info> <booklist> <book> <name>Java设计模式</name> <price>150</price> </book> <book> <name>三国演义</name> <price>200</price> </book> <book> <name>水浒传</name> <price>300</price> </book> </booklist> <picturelist> <pirture> <name>图片1</name> <price>100</price> </pirture> <pirture> <name>图片2</name> <price>200</price> </pirture> </picturelist></info>
只针对book。 picture的可以先不看
------解决方案--------------------------------------------------------
你可以网上查找先jdom dom4j sax ... 等等几种解析与操作xml文件的资料,一般都有实际代码给你参考的
------解决方案--------------------------------------------------------
- Java code
File file = new File("D:\\test.xml"); SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element dicts = (Element) doc.selectSingleNode("/info/booklist"); Element bookElement = dicts.addElement("book"); Element name = bookElement.addElement("name"); name.addText("水浒传"); Element price = bookElement.addElement("price"); price.addText("300"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); writer.write(doc); writer.close();