XML parsing----XML parsing method in Java 4 (reproduced)

Source: Internet
Author: User

Reprint: https://www.cnblogs.com/longqingyang/p/5577937.html

Describe

XML is a kind of universal data Interchange Format, its platform-independent, language-independent, system-independent, to the data integration and interaction brings great convenience. XML is interpreted the same way in different locales, except for the syntax that is implemented differently.

XML parsing methods are divided into four kinds: 1, Dom parsing, 2, sax parsing, 3, Jdom parsing, 4, dom4j parsing. The first two are the basic methods, the official platform-independent parsing method, the latter two are extension methods, they are expanded on the basis of the method, only applicable to the Java platform.

Four ways are described in detail for the following XML file:

<?xml version= "1.0" encoding= "UTF-8"?><bookstore>    <book id= "1" >        <name> Song of Ice and Fire </ Name>        <author> George Martin </author>        <year>2014</year>        <price>89</price >        <language>Chinese</language>    </book>    <book id= "2" >        <name> Andersen fairy tale </name>        <year>2004</year>        <price>77</price>        <language> english</language>    </book>    </bookstore>

Based on the above XML file structure, we can build a corresponding model class:

Package Xmlanaly;public class Book {private String id = "";p rivate string name = "";p rivate string author = "";p rivate Str ING year = "";p rivate string price = "";p rivate String language = "";p ublic string GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getauthor () {return author;} public void Setauthor (String author) {this.author = author;} Public String GetYear () {return year;} public void Setyear (String year) {this.year = year;} Public String GetPrice () {return price;} public void Setprice (String price) {this.price = Price;} Public String GetLanguage () {return language;} public void SetLanguage (String language) {this.language = language;}}

First, Dom parsing

The full name of the DOM is the Document Object model, which is also known as the documentation. In an application, the DOM-based XML parser transforms an XML document into a collection of object models (often called the DOM tree), and the application is manipulating the XML document data through the operation of the object model. Through the DOM interface, an application can access any part of the data in an XML document at any time, so this mechanism of using the DOM interface is also called a random access mechanism.

The DOM interface provides a way to access XML document information through a hierarchical object model, which forms a tree of nodes based on the document structure of the XML. Regardless of the type of information described in the XML document, even if it is a table of data, a list of items, or a document, the model generated by using the DOM is in the form of a node tree. That is, the DOM enforces the use of the tree model to access the information in the XML document. Because XML is essentially a hierarchical structure, this method of description is quite effective.

The random access provided by the DOM tree provides a lot of flexibility in the development of the application, and it can control the content of the entire XML document in any arbitrary way. However, because the DOM parser transforms the entire XML document into a DOM tree in memory, the need for memory is higher when the document is larger or the structure is more complex. Also, the traversal of a complex tree is a time-consuming operation. Therefore, the DOM parser has higher requirements for machine performance and is not very efficient to achieve. However, because the idea of tree structure adopted by DOM parser is consistent with the structure of XML document, and because of the convenience of random access, Dom parser has a wide use value.

Advantages:

1, the formation of a tree structure, to facilitate better understanding, mastery, and code easy to write.

2, in the process of parsing, the tree structure is stored in memory, easy to modify.

Disadvantages:

1, because the file is a one-time read, so the cost of memory is relatively large.

2, if the XML file is larger, it is easy to affect the parsing performance and may cause memory overflow.

The following is the parsing code:

Import Java.io.ioexception;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.parsers.parserconfigurationexception;import Org.w3c.dom.document;import Org.w3c.dom.namednodemap;import Org.w3c.dom.node;import Org.w3c.dom.NodeList;import Org.xml.sax.saxexception;public class Domtest {public static void main (string[] args) {//Create a Documentbuilderfactory object, PS This is a Documentbuilder production plant documentbuilderfactory dbf = documentbuilderfactory.newinstance (); try {// Create a Documentbuilder object Documentbuilder db = Dbf.newdocumentbuilder ();// Loading the Test.xml file into the current directory with the parse method of the Documentbuilder object is the org.w3c.domDocument document = Db.parse ("Xml\\test.xml") of the package imported here:// Gets the collection of all the nodes of this XML file nodelist testlist = document.getElementsByTagName ("book"); System.out.println ("A total" + testlist.getlength () + "book");//Traverse all nodes for (int i=0; i<testlist.getlength (); i++) { SYSTEM.OUT.PRINTLN ("-----" + (i+1) + "-----");//through the item (i) method, get a book node, nodelist so starting from 0 node book = testlist.item (i) ;//Get BooAll attribute sets of K-node NamedNodeMap attrs = Book.getattributes (); SYSTEM.OUT.PRINTLN ("-----" + (i+1) + "book in total" + attrs.getlength () + "Properties-----");//traverse the properties of the books for (int j=0; j< Attrs.getlength (); J + +) {///through Item (j), get each child node of book, that is, attribute node attr = Attrs.item (j);//Read property name and property value System.out.print ("Name:" + Attr.getnodename ()); System.out.println ("Value:" + attr.getnodevalue ());} Parse the child node of the book node nodelist childNodes = Book.getchildnodes ();//traverse ChildNodes Get the node dream and node value of each node System.out.println ("+" + (i+1) + "Total book" + childnodes.getlength () + "child Node"); for (int k=0; k<childnodes.getlength (); k++) {// Distinguishes between Node of type Test and Nodeif of ELEMENT type (Childnodes.item (k). Getnodetype () = = Node.element_node) {// Gets the node name of the element type node System.out.print ("The node name of" + (k + 1) + "node:" + Childnodes.item (k). Getnodename ());// Gets the node value of the element type node System.out.println ("Node value is:" + Childnodes.item (k). Getfirstchild (). Getnodevalue ());}} SYSTEM.OUT.PRINTLN ("-----" + (i+1) + "End of book-----");}} catch (Parserconfigurationexception e) {e.printstacktrace ();} catch (Saxexception e) {E.printstacKtrace ();} catch (IOException e) {e.printstacktrace ();}}}

Second, sax parsing

  The full name of Sax is the simple API for XML, also known as the XML trivial application interface. Unlike the DOM, the access pattern provided by Sax is a sequential pattern, which is a way to read and write XML data quickly. When parsing an XML document using the SAX parser, a series of events are triggered and the corresponding event handlers are activated, and the application accesses the XML document through these event handlers, and the Sax interface is also referred to as the event-driven interface.

Advantages:

1, the use of event-driven mode, the memory cost is relatively small.

2, for processing only the data in the XML file.

Disadvantages:

1, the code is more troublesome.

2, it is difficult to access many different data in the XML file at the same time.

The following is the parsing code:

Import Java.util.arraylist;import Java.util.list;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;public class Saxtest {public static void main (string[] args) {saxparserfactory Factory = Saxparserfactory.newinstance (); try {saxparser parser = Factory.newsaxparser (); Saxparserhandler handler = new Saxparserhandler ();p arser.parse ("Xml\\test.xml", Handler); System.out.println ("----------Total" + handler.getbooklist (). Size () + "book------------");                Handler.getbooklist ()) {System.out.println (Book.getid ());                System.out.println (Book.getname ());                System.out.println (Book.getauthor ());                System.out.println (Book.getyear ());                System.out.println (Book.getprice ());                System.out.println (Book.getlanguage ()); System.out.println ("----finish----");}} catch (Exception e) {e.printstacktrace ();}}}class Saxparserhandler extends defaulthandler{string value = null; Book book = null;private list<book> Booklist = new arraylist<> ();p ublic list<book> getbooklist () { return Booklist;} int bookindex = 0;//used to identify the parsing start @overridepublic void Startdocument () throws Saxexception {super.startdocument (); System.out.println ("Sax parsing Begins");} Used to identify the parsing end @overridepublic void Enddocument () throws Saxexception {super.enddocument (); System.out.println ("Sam parsing End");} Parsing xml@overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception {//calls the Startelement method of the DefaultHandler class Super.startelement (URI, LocalName, qName, attributes); Qname.equals ("book")) {book = new book (); SYSTEM.OUT.PRINTLN ("------begins to traverse the contents of a book-------"); int num = Attributes.getlength (); for (int i=0; i<num; i++) {                System.out.print ("The book Element's" + (i + 1) + "attribute name is:" + attributes.getqname (i));                System.out.println ("attribute value is:" + attributes.getvalue (i)); if (ATTRIBUTES.GEtqname (i). Equals ("id")) {Book.setid (Attributes.getvalue (i)); }}}else if (!qname.equals ("name") &&!qname.equals ("bookstore") {System.out.print ("node name is:" + QName + "");}} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {super.endelement (URI, LocalName, qName);//Determine whether a book has been facilitated by the end of the IF ("Qname.equals (") ") {Booklist.add (books); SYSTEM.OUT.PRINTLN ("------to end the traversal of a book-------");} else if (qname.equals ("name")) {Book.setname (value);} else if (qname.equals ("author")) {Book.setauthor (value);} else if (Qname.equals ("year")) {book.setyear (value);} else if (qname.equals ("price")) {Book.setprice (value);} else if (qname.equals ("language")) {book.setlanguage (value);}} @Overridepublic void characters (char[] ch, int start, int length) throws saxexception {super.characters (ch, start, length) ; value = new String (CH, start, length), if (!value.trim (). Equals ("")) {System.out.println ("node value is:" + value);}}

 Three, jdom analysis

Characteristics:

1. Use only specific classes, not interfaces.

2, the API uses the collections class extensively.

Need to import Jdom.jar

The following is the parsing code:

Import Java.io.fileinputstream;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.util.arraylist;import Java.util.list;import Org.jdom.attribute;import Org.jdom.document;import Org.jdom.element;import Org.jdom.input.saxbuilder;public class Jdomtest {private static list<book> BooksList = New Arraylist<> ();p ublic static void Main (string[] args) {//Create a Saxbuilder object Saxbuilder saxbuilder = new Saxbuilder (); InputStream In;try {//Read into XML file in = new FileInputStream ("Xml\\test.xml"); InputStreamReader ISR = new InputStreamReader (In, "utf-8");//The XML input stream is loaded into saxbuilderdocument document = Saxbuilder.build (ISR) through the Saxbuilder build method;// Gets the root node of the xml file Element rootelement = Document.getrootelement ();//Gets the list collection under the child node of the root node list<element> Booklist = Rootelement.getchildren ();//Continue parsing for (Element book:booklist) {Book bookentity = new book (); SYSTEM.OUT.PRINTLN ("-------begin to parse the first" + (Booklist.indexof (book) + 1) + "books--------"); Attrlist = Book.getattributes ();Get the node value//Book.getattributevalue ("id") when you know the name of the property under the node; Traverse Attrlist (for unclear name and number of attributes under the book node) for (Attribute attr:attrlist) {String attrname = Attr.getname (); String AttrValue = Attr.getvalue (); System.out.println ("Property name:" + attrname + "property value:" + attrValue), if (Attrname.equals ("id")) {Bookentity.setid (AttrValue);}} Iterates over the child node name and child node values of the book nodes list<element> bookchilds = Book.getchildren (); for (Element Child:bookchilds) { System.out.println ("Node name:" + child.getname () + "node value:" + child.getvalue ()), if (Child.getname (). Equals ("name")) { Bookentity.setname (Child.getvalue ());} else if (Child.getname (). Equals ("author")) {Bookentity.setauthor (Child.getvalue ());} else if (Child.getname (). Equals ("year")) {Bookentity.setyear (Child.getvalue ());} else if (Child.getname (). Equals ("price")) {Bookentity.setprice (Child.getvalue ());} else if (Child.getname (). Equals ("language")) {Bookentity.setlanguage (Child.getvalue ());}} System.out.println ("--------End parsing" + (Booklist.indexof (book) + 1) + "books--------"); Bookslist.add (bookentity); bookentity = null; System.out.println (Bookslist.size ()); System.out.println (Bookslist.get (0). GetId ()); System.out.println (Bookslist.get (0). GetName ());}} catch (Exception e) {//Todo:handle Exception}}}

4, DOM4J analysis

Characteristics:

1. An intelligent branch of Jdom, which incorporates many functions beyond the basic XML document representation.

2. It uses interfaces and abstract basic class methods.

3, with excellent performance, flexibility, powerful and extremely easy to use features.

4, is an open-source file

Need to import Dom4j.jar package

The following is the parsing code:

Import Java.util.iterator;import java.util.list;import Org.dom4j.attribute;import Org.dom4j.document;import Org.dom4j.element;import Org.dom4j.io.saxreader;public class Dom4jtest {public static void main (string[] args) {// Create a Saxreader object Saxreader reader = new Saxreader (); try {////through the Read method of the reader method to load the XML file, get the Document Object Document document = Reader.read ("Xml\\test.xml");//Gets the root node bookstoreelement bookstore = Document.getrootelement () through the Document object;// Gets the iterator iterator it = bookstore.elementiterator () by means of the element object, while (It.hasnext ()) {System.out.println ("-------- Begin to traverse the first book--------"); Element book = (element) it.next ();//Gets the property name of the book and the property value list<attribute> bookattrs = Book.attributes (); for (Attribute Attr:bookattrs) {System.out.println ("Property name:" + attr.getname () + "property value:" + attr.getvalue ());} Gets the node name and node value of the child node iterator ITT = Book.elementiterator (); while (Itt.hasnext ()) {element bookchild = (Element) Itt.next (); System.out.println ("Node name:" + bookchild.getname () + "node value:" + bookchild.getstringvalue ());} System.out.prIntln ("--------End the traversal of a book--------");}} catch (Exception e) {//Todo:handle Exception}}}

Final: Comparison Summary

DOM4J performance is the best, even Sun's JAXM is also in use dom4j. Many open source projects currently employ dom4j, such as the famous Hibernate, which also uses DOM4J to read XML configuration files. If portability is not considered, then dom4j is used.
Jdom and Dom perform poorly during performance testing, and memory overflows when testing 10M documents. In the case of small documents it is also worth considering Dom and Jdom. Although Jdom developers have stated that they expect to focus on performance issues before the full release, there is no merit in the performance perspective. In addition, Dom is still a very good choice. DOM implementations are widely used in many programming languages. It is also the basis for many other XML-related standards, because it is formally recommended (as opposed to a non-standard Java model), so it may also be needed in some types of projects (such as using the DOM in JavaScript).
Sax behaves better, depending on its specific parsing-event-driven behavior. A sax detects the incoming XML stream, but does not load into memory (of course, some documents are temporarily hidden in memory when the XML stream is read).

XML parsing----XML parsing method in Java 4 (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.