JAVA manipulation XML instance analysis
- 2020-04-01 03:45:01
- OfStack
This article illustrates how JAVA can manipulate XML. Share with you for your reference. The details are as follows:
The Java code is as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
Element theBook=null, theElem=null, root=null;
try {
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder db=factory.newDocumentBuilder();
Document xmldoc=db.parse(new File("Test1.xml"));
root=xmldoc.getDocumentElement();
theBook=(Element) selectSingleNode("/books/book[name=' Harry potter ']", root);
System.out.println("--- Search for harry potter ----");
Element nameNode=(Element)theBook.getElementsByTagName("price").item(0);
String name=nameNode.getFirstChild().getNodeValue();
System.out.println(name);
output(theBook);
System.out.println("=============selectSingleNode(books/book[name=' Harry potter '], root)==================");
//-- new book to start --
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent(" A new book ");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("memo");
theElem.setTextContent(" The new book is better. ");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- Start with a new book ----");
output(xmldoc);
System.out.println("==============================");
//-- new book completed --
//-- make some changes to harry potter. - < br / >
//-- looking for harry potter -- < br / >
//-- now revise the price of this book --
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName Returns the NodeList So keep up item(0) . In addition, getElementsByTagName("price") The equivalent of xpath the ".//price" .
System.out.println("--- Revise the price of this book at this time ----");
output(theBook);
//-- we also want to add an attribute id of B01 --
theBook.setAttribute("id", "B01");
System.out.println("--- I also want to add a property id And has a value of B01 ----");
output(theBook);
//-- finishing the revision of harry potter. - < br / >
//-- to use the id attribute to delete "romance of The Three Kingdoms" this book --
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- Want to use id Property delete "romance of The Three Kingdoms" this book ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- The deleted XML ----");
output(xmldoc);
//-- delete all books below the price of 10 --
NodeList someBooks=selectNodes("/books/book[price<10]", root);
System.out.println("--- And then lower all the prices 10 Book to delete ---");
System.out.println("--- Qualified books are available "+someBooks.getLength()+" Ben. ---");
for(int i=0;i<someBooks.getLength();i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);
saveXml("Test1_Edited.xml", xmldoc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void output(Node node) {//Output the XML string of the node to the console
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
source.setNode(node);
StreamResult result=new StreamResult();
result.setOutputStream(System.out);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
public static Node selectSingleNode(String express, Object source) {//Find the node and return the first qualified node
Node result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static NodeList selectNodes(String express, Object source) {//Find the node and return the set of nodes that meet the criteria. < br / >
NodeList result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
public static void saveXml(String fileName, Document doc) {//Output the Document to a file
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
DOMSource source=new DOMSource();
source.setNode(doc);
StreamResult result=new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
The XML file is as follows:
<?xml version="1.0" encoding="GBK"?>
<books>
<book>
<name> Harry potter </name>
<price>10</price>
<memo> This is a very good book. </memo>
</book>
<book id="B02">
<name> The romance of The Three Kingdoms </name>
<price>10</price>
<memo> One of the four great classical novels. </memo>
</book>
<book id="B03">
<name> Water margin </name>
<price>6</price>
<memo> One of the four great classical novels. </memo>
</book>
<book id="B04">
<name> Red chamber </name>
<price>5</price>
<memo> One of the four great classical novels. </memo>
</book>
</books>
I hope this article has been helpful to your Java programming.