JAVA操作XML实例分析
本文实例讲述了JAVA操作XML的方法。分享给大家供大家参考。具体如下:
java代码如下:
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.w3c.dom.*;
importorg.xml.sax.SAXException;
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=db.parse(newFile("Test1.xml"));
root=xmldoc.getDocumentElement();
theBook=(Element)selectSingleNode("/books/book[name='哈里波特']",root);
System.out.println("---查询找《哈里波特》----");
ElementnameNode=(Element)theBook.getElementsByTagName("price").item(0);
Stringname=nameNode.getFirstChild().getNodeValue();
System.out.println(name);
output(theBook);
System.out.println("=============selectSingleNode(books/book[name='哈里波特'],root)==================");
//---新建一本书开始----
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);
System.out.println("==============================");
//---新建一本书完成----
//---下面对《哈里波特》做一些修改。----
//---查询找《哈里波特》----
//---此时修改这本书的价格-----
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<someBooks.getLength();i++){
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);
saveXml("Test1_Edited.xml",xmldoc);
}catch(ParserConfigurationExceptione){
e.printStackTrace();
}catch(SAXExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidoutput(Nodenode){//将node的XML字符串输出到控制台
TransformerFactorytransFactory=TransformerFactory.newInstance();
try{
Transformertransformer=transFactory.newTransformer();
transformer.setOutputProperty("encoding","gb2312");
transformer.setOutputProperty("indent","yes");
DOMSourcesource=newDOMSource();
source.setNode(node);
StreamResultresult=newStreamResult();
result.setOutputStream(System.out);
transformer.transform(source,result);
}catch(TransformerConfigurationExceptione){
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}
}
publicstaticNodeselectSingleNode(Stringexpress,Objectsource){//查找节点,并返回第一个符合条件节点
Noderesult=null;
XPathFactoryxpathFactory=XPathFactory.newInstance();
XPathxpath=xpathFactory.newXPath();
try{
result=(Node)xpath.evaluate(express,source,XPathConstants.NODE);
}catch(XPathExpressionExceptione){
e.printStackTrace();
}
returnresult;
}
publicstaticNodeListselectNodes(Stringexpress,Objectsource){//查找节点,返回符合条件的节点集。
NodeListresult=null;
XPathFactoryxpathFactory=XPathFactory.newInstance();
XPathxpath=xpathFactory.newXPath();
try{
result=(NodeList)xpath.evaluate(express,source,XPathConstants.NODESET);
}catch(XPathExpressionExceptione){
e.printStackTrace();
}
returnresult;
}
publicstaticvoidsaveXml(StringfileName,Documentdoc){//将Document输出到文件
TransformerFactorytransFactory=TransformerFactory.newInstance();
try{
Transformertransformer=transFactory.newTransformer();
transformer.setOutputProperty("indent","yes");
DOMSourcesource=newDOMSource();
source.setNode(doc);
StreamResultresult=newStreamResult();
result.setOutputStream(newFileOutputStream(fileName));
transformer.transform(source,result);
}catch(TransformerConfigurationExceptione){
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
}
}XML文件如下:
<?xmlversion="1.0"encoding="GBK"?> <books> <book> <name>哈里波特</name> <price>10</price> <memo>这是一本很好看的书。</memo> </book> <bookid="B02"> <name>三国演义</name> <price>10</price> <memo>四大名著之一。</memo> </book> <bookid="B03"> <name>水浒</name> <price>6</price> <memo>四大名著之一。</memo> </book> <bookid="B04"> <name>红楼</name> <price>5</price> <memo>四大名著之一。</memo> </book> </books>
希望本文所述对大家的java程序设计有所帮助。