Java对XML文件增删改查操作示例
本文实例讲述了Java对XML文件增删改查操作。分享给大家供大家参考,具体如下:
xml文件:
哈里波特 10 这是一本很好看的书。 三国演义 10 四大名著之一。 水浒 6 四大名著之一。 红楼 5 四大名著之一。
增删改查Test.java
importjava.io.File;
importjava.io.FileOutputStream;
importorg.w3c.dom.*;
importjavax.xml.parsers.*;
importjavax.xml.transform.*;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.*;
importjavax.xml.xpath.*;
publicclassTest{
publicstaticvoidmain(String[]args){
DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();
ElementtheBook=null,theElem=null,root=null;
try{
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilderdb=factory.newDocumentBuilder();
Documentxmldoc=(Document)db.parse(newFile("Test.xml"));
root=xmldoc.getDocumentElement();
//---新建一本书开始----
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent("新书");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("memo");
theElem.setTextContent("新书的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("---新建一本书开始----");
output(xmldoc);
//---新建一本书完成----
//---下面对《哈里波特》做一些修改。----
//---查询找《哈里波特》----
theBook=(Element)selectSingleNode("/books/book[name='哈里波特']",
root);
System.out.println("---查询找《哈里波特》----");
output(theBook);
//---此时修改这本书的价格-----
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的".//price"。
System.out.println("---此时修改这本书的价格----");
output(theBook);
//---另外还想加一个属性id,值为B01----
theBook.setAttribute("id","B01");
System.out.println("---另外还想加一个属性id,值为B01----");
output(theBook);
//---对《哈里波特》修改完成。----
//---要用id属性删除《三国演义》这本书----
theBook=(Element)selectSingleNode("/books/book[@id='B02']",root);
System.out.println("---要用id属性删除《三国演义》这本书----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("---删除后的XML----");
output(xmldoc);
//---再将所有价格低于10的书删除----
NodeListsomeBooks=selectNodes("/books/book[price<10]",root);
System.out.println("---再将所有价格低于10的书删除---");
System.out.println("---符合条件的书有"+someBooks.getLength()
+"本。---");
for(inti=0;i
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具: