2017/4/26-DOM Parse XML file, 201726-dom

Source: Internet
Author: User
Tags xml file example

2017/4/26-DOM Parse XML file, 201726-dom

DOM parsing XML

1,Analysis

DOM is an XML parsing API that comes with JAVA. DOM first loads all XML files into the memory, and then creates a DOM tree in the memory to generate each Node on the DOM tree.

 

2,Advantages

1) You can create or modify the content of an XML file.

2) perform XSLT conversion.

3) perform Xpath filtering.

 

3,Disadvantages

1) Because DOM loads the XML file to the memory and uses the DOM tree, when the file is too large, it occupies a lot of memory.

2) compared with SAX, the efficiency also decreases significantly.

 

4,Applicable scenarios

1) You can use DOM to modify or create an XML document.

2) When the XML file is very small, you can ignore the memory size occupied after loading. You can use DOM.

3) DOM can be used for XSLT conversion or Xpath filtering.

 

5,Explanations

1) Compared with SAX, DOM development is relatively small.

2) obtain the DocumentBuilderFactory object from DocumentBuilderFactory and use the newInstance () method.

3) obtain the DocumentBuilder object from the object in step 2 and use the newDocumentBuilder () method.

4) convert the xml file to a Document object and load it to the memory. Use the parse (InputStream is) method of the object in step 3. The "is" parameter is the input stream of the XML file.

5) use the Document object to pass the Element Object. This Element object is the root node.

6) determine whether a subnode exists under the root Node. If yes, traverse and obtain the Node object. If yes, the Node object is a subnode.

7) determine whether there are other subnodes under the subnode. If so, traverse and so on. (Recursive queries can be used)

 

6,Details

1) XML file example

<?xml version="1.0" encoding="utf-8"?><books>    <book>        <id>10001</id>        <name>JAVA BOOK</name>        <author>James Gosling</author>        <publishDate>2017-04-24</publishDate>    </book>    <book>        <id>10002</id>        <name>C BOOK</name>        <author>Dennis Ritchie</author>        <publishDate>2017-04-24</publishDate>    </book></books>
View Code

2) DOM parsing XML file demo

Package com. mean. xml. dom. demo; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList;/*** @ author mean **/public class DomDemo {public DomDemo () {}/ *** main XML Parsing Method for DOM **/public static void analysis () {DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory. newInstance (); try {DocumentBuilder domBuilder = domBuilderFactory. newDocumentBuilder (); Document dom = domBuilder. parse (DomDemo. class. getResourceAsStream ("/Book. xml "); Element books = dom. getDocumentElement (); // root node (books) if (books. hasChildNodes () {NodeList booksList = books. getChildNodes (); for (int I = 0, l = booksList. getLength (); I <l; I ++) {Node book = booksList. item (I); // sub-node (book) if (book. hasChildNodes () {NodeList bookList = book. getChildNodes (); System. out. println ("---------- book content ----------"); for (int j = 0, len = bookList. getLength (); j <len; j ++) {Node sonNode = bookList. item (j); // subnode (id, name, author, publishData) under the book if (sonNode. getNodeType () = Element. ELEMENT_NODE) {System. out. println ("nodeName:" + sonNode. getNodeName () + ", nodeValue:" + sonNode. getTextContent (). trim () ;}}}} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) {DomDemo. analysis ();}}
View Code

3) Parse XML files by DOM and recursively traverse each node demo (use with caution)

Package com. mean. xml. dom. demo; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList;/*** recursively traverse nodes * @ author mean */public class DomTraversalNodeDemo {public DomTraversalNodeDemo () {}/*** main method for DOM parsing XML **/public static void analysis () {DocumentBuilderF Actory domBuilderFactory = DocumentBuilderFactory. newInstance (); try {DocumentBuilder domBuilder = domBuilderFactory. newDocumentBuilder (); Document dom = domBuilder. parse (DomDemo. class. getResourceAsStream ("/Book. xml "); Element books = dom. getDocumentElement (); // root node (books) if (books. hasChildNodes () {NodeList booksList = books. getChildNodes (); for (int I = 0, l = booksList. getLength (); I <L; I ++) {Node book = booksList. item (I); // sub-node (book) if (book. getNodeType () = Element. ELEMENT_NODE) {System. out. println ("--------- book -----------"); traversalNode (book) ;}}} catch (Exception e) {e. printStackTrace () ;}/ *** traverse subnode **/public static void traversalNode (Node node) {// this judgment is made to prevent line feed output, because the DOM will press enter as a node if (node. getNodeType ()! = Element. TEXT_NODE) {// if there are subnodes under the node, traverse the node if (node. hasChildNodes () {NodeList nodeList = node. getChildNodes (); if (nodeList. getLength () = 1 & (nodeList. item (0 ). getNodeType () = Element. TEXT_NODE) {System. out. println ("nodeName:" + node. getNodeName () + ", nodeValue:" + node. getTextContent (). trim ();} else {for (int I = 0, l = nodeList. getLength (); I <l; I ++) {Node sonNode = nodeList. item (I); traversalNode (sonNode) ;}}} public static void main (String [] args) {DomTraversalNodeDemo. analysis ();}}
View Code

 

7,Reference

1) This article draws on the blog Web site: http://blog.csdn.net/zhangxinrun/article/details/5678118

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.