Java Parsing XML Rollup
Keywords: Java parsing XML, parsing XML four methods, DOM, SAX, JDOM, dom4j, XPath
"Introduction"
There are many techniques for parsing XML in Java, the mainstream is DOM, SAX, JDOM, dom4j, the following is mainly about the use, advantages and disadvantages of these 4 parsing XML document technology and performance test. first, "basic knowledge-Literacy"
Sax and Dom are two methods of parsing XML documents (not specifically implemented, just interfaces), so only they cannot parse XML documents; JAXP is just an API that further encapsulates the sax, Dom two interfaces, Domcumentbuilderfactory/domcumentbuilder and Saxparserfactory/saxparser are also provided (the default is to use the Xerces interpreter). "DOM, SAX, JDOM, dom4j simple Use Introduction"
1, "DOM (Document Object Model)"
The interface provided by the consortium, which reads the entire XML document into memory and constructs a DOM tree to operate on individual nodes (node). Defines a set of interfaces for the parsed version of an XML document. The parser reads the entire document and then constructs a tree that resides in memory, and then the code can manipulate the tree structure using the DOM interface.
Advantages: The entire document tree in memory, easy to operate, support delete, modify, rearrange and so on a variety of functions.
Disadvantage: The entire document is being transferred into memory (including unwanted nodes), wasting time and space.
Usage: Once the document is parsed, the data needs to be accessed multiple times, with sufficient hardware resources (memory, CPU).
Sample code: <?xml version= "1.0" encoding= "UTF-8"?> <university name= "PKU" > <college name= "C1" > <class name= "Class1" > <student name= "stu1" sex= ' Male ' age= ' /> <student name= "STU2" sex= ' Female ' age= /> <student name= "Stu3" sex= ' female ' age= ' /> </class> <class name= "Class2" > <student&nbSp;name= "Stu4" sex= ' Male ' age= ' /> <student name= "Stu5" sex= ' female ' age= ' /> <student name= "Stu6" sex= ' female ' age= ' /> </ class> </college> <college name= "C2" > <class name= "CLASS3" > <student name= "Stu7" sex= ' Male ' age= ' /> </class> </college> < College name= "C3"> </college> </university>
The following code is used to Text.xml (the document is placed under the SRC path, both compiled and under the classes path), referring to the XML document. package test.xml; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import javax.xml.parsers.documentbuilder; import javax.xml.parsers.documentbuilderfactory; import javax.xml.parsers.parserconfigurationexception;