XML series: (4) XML parsing-JAXP Dom parsing method reading XML

Source: Internet
Author: User


DOM, sax, and Stax are just parsing methods, without APIs.

JAXP is a set of XML parsing APIs provided by Sun. JAXP (Java API for xmlprocessing, meaning XML-processed Java API)

JAXP is good at supporting DOM and sax parsing.

The JAXP Development Kit is part of the javase, which consists of Java.xml, Org.w3c.dom, org.xml.sax packages and their child packages


Products.mxl

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE products[<! ELEMENT Products (product+) > <! ELEMENT product (name,price) > <! ELEMENT name (#PCDATA) > <! ELEMENT Price (#PCDATA) > <!      Attlist Product ID #REQUIRED >]><products> <product id= "P001" > <name> the past is not like smoke </name>      <price>49.9 </price> </product> <product id= "P002" > <name> siege </name> <price>59.9 Yuan </price> </product></products>


1. Reading XML in DOM parsing mode


1.1. Read an element by ID
package com.rk.xml.d_jaxp_dom;import javax.xml.parsers.documentbuilderfactory;import  javax.xml.parsers.documentbuilder;import org.w3c.dom.document;import org.w3c.dom.element;/** *   reads an element by ID  *  gets an element by using the document.getElementById (String elementid) method  *   @author  rk * */public class demo01{public static void main ( String[] args) &NBSP;THROWS&NBSP;EXCEPTION{//1, new to the parser factory//2, through the parser factory to get the parser object//3, parsing the XML document through the parser object, and return the Document Object/ /4, through the Document object to get the node node//1, new to get the parser factory documentbuilderfactory builderfactory =  Documentbuilderfactory.newinstance ();///2, through the parser factory to get the parser object documentbuilder builder =  Builderfactory.newdocumentbuilder ();//3, parses the XML document through the parser object, and returns the Document object document doc =  Builder.parse ("./src/products.xml");//4, through the document object to get the node Nodeelement elem = doc.getelementbyid ( "P001");//must use the DTD declaration id attribute System.out.println (elem);//[product: null]sYstem.out.println (Elem.getnodetype ());//1 element type node is represented by 1 System.out.println (Elem.getnodename ());// ProductSystem.out.println (Elem.getnodevalue ());//nullsystem.out.println (Elem.gettextcontent ());//The past is not as smoke 49.9 Yuan}}



1.2. Read a series of nodes (NodeList)
package com.rk.xml.d_jaxp_dom;import javax.xml.parsers.documentbuilderfactory;import  Javax.xml.parsers.documentbuilder;import org.w3c.dom.document;import org.w3c.dom.nodelist;import  org.w3c.dom.Node;/** *  read a series of nodes (NodeList)  *  via document.getElementsByTagName (String  tagname) Gets a series of nodes.  *  @author  RK * */public class Demo02{public static void  Main (String[] args) &NBSP;THROWS&NBSP;EXCEPTION{//1, new to the parser factory//2, through the parser factory to get the parser object//3, through the Parser object parsing XML document, and return the Document object//4, through the document object to get the node node//1, new to get the parser factory documentbuilderfactory builderfactory =  Documentbuilderfactory.newinstance ();///2, through the parser factory to get the parser object documentbuilder builder =  Builderfactory.newdocumentbuilder ();//3, parses the XML document through the parser object, and returns the Document object document doc =  Builder.parse ("./src/products.xml");//4, through the document object to get the node nodenodelist list =  Doc.getelementsbytagname ("Product"); System.out.println ("Find" +list.gEtlength () + "a");//Find out how many nodes for (Int i=0;i<list.getlength (); i++) {Node node = list.item (i); SYSTEM.OUT.PRINTLN (node);//Print the Individual nodes}}}



1.3. Read an attribute (Attribute)
package com.rk.xml.d_jaxp_dom;import javax.xml.parsers.documentbuilderfactory;import  javax.xml.parsers.documentbuilder;import org.w3c.dom.document;import org.w3c.dom.node;import  org.w3c.dom.nodelist;import org.w3c.dom.namednodemap;/** *  reads an attribute (Attribute)  * @ Author rk * */public class demo03{public static void main (String[]  args)  throws Exception{DocumentBuilderFactory builderFactory =  Documentbuilderfactory.newinstance ();D ocumentbuilder builder =  Builderfactory.newdocumentbuilder ();D ocument doc = builder.parse ("./src/products.xml"); Nodelist list = doc.getelementsbytagname ("Product"); Node node = list.item (0); Namednodemap map =  node.getattributes ();//Gets the node to all attribute types node attrnode =  Map.getnameditem ("id");//Gets the node System.out.println (Attrnode.getnodetype ()) with the property "id";//2  Property (ATtribute) Type of node is represented by 2 System.out.println (Attrnode.getnodename ());//idsystem.out.println (Attrnode.getnodevalue ()); /p001system.out.println (Attrnode.gettextcontent ());//p001}}



1.4. Read the text of an element
Package Com.rk.xml.d_jaxp_dom;import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.parsers.documentbuilder;import Org.w3c.dom.document;import Org.w3c.dom.nodelist;import Org.w3c.dom.Node ;/** * Read text of an element * @author RK * */public class demo04{public static void Main (string[] args) throws Exception{docume Ntbuilderfactory builderfactory = documentbuilderfactory.newinstance ();D Ocumentbuilder builder = Builderfactory.newdocumentbuilder ();D ocument doc = Builder.parse ("./src/products.xml"); NodeList list = doc.getelementsbytagname ("name"); Node node = list.item (0); System.out.println (Node.gettextcontent ());//The past is not as smoke}}




1.5. Traverse Document Object Tree
package com.rk.xml.d_jaxp_dom;import javax.xml.parsers.documentbuilderfactory;import  Javax.xml.parsers.documentbuilder;import org.w3c.dom.document;import org.w3c.dom.nodelist;import  org.w3c.dom.Node;import org.w3c.dom.NamedNodeMap;/** *  Traverse all nodes  *  @author  rk  * */public class demo05{public static void main (String[] args)   throws exception{documentbuilderfactory builderfactory =  Documentbuilderfactory.newinstance ();D ocumentbuilder builder =  Builderfactory.newdocumentbuilder ();D ocument doc = builder.parse ("./src/products.xml"); Stringbuilder sb = new stringbuilder (); Nodelist childnodes = doc.getchildnodes (); for (Int i=0;i<childnodes.getlength (); i++) { Node node = childnodes.item (i); System.out.println (Node.getnodetype ()  +  "= = ="  + node.getnodename () +  "= = ="  +&Nbsp;node.getnodevalue ());} /* Output Result: 10===products===nulldocument_type_node        = 101=== products===null element_node               = 1 */traversedocument (Doc.getlastchild (), SB); System.out.println (Sb.tostring ());/*  output result:  <products ><product id= "P001"   ><name > the past is not like smoke </name><price >49.9 yuan </price></product><product  id= "P002"  ><name > siege </name><price >59.9 Yuan </price></product ></products> */}private static void traversedocument (Node node,  STRINGBUILDER&NBSP;SB) {//1, Current element start Sb.append ("<"  + node.getnodename ()  +  " ");//2, Gets the property if (Node.hasattributes ()) {namednodemap nodemap = node.getattributes (); for (int i=0;i< Nodemap.getlength (); i++) {NODE&NBSP;ATTRNODE&NBSP;=&NBSp;nodemap.item (i); Sb.append (Attrnode.getnodename ()  +  "=\" " + attrnode.getnodevalue ()  +  "\"   ");}} Sb.append (">");//3, get child Nodes nodelist childnodes = node.getchildnodes (); for (int i=0;i< Childnodes.getlength (); i++) {Node subnode = childnodes.item (i);short type =  Subnode.getnodetype (); if (type == 1)//current node is element node {traversedocument (SUBNODE,&NBSP;SB);} Else if (type == 3)//Current node is the text node {sb.append (Subnode.gettextcontent ());} else{//other cases, do not handle}}//4, current element end Sb.append ("</"  + node.getnodename ()  +  ">");}}







2. Mind Mapping

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/80/0E/wKioL1c1yi6BT_l9AAF49VEDzyg283.png "title=" jaxp_ Dom.png "alt=" Wkiol1c1yi6bt_l9aaf49vedzyg283.png "/>







XML series: (4) XML parsing-JAXP Dom parsing method reading XML

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.