XML document
<?xml version= "1.0" encoding= "UTF-8"? ><bookstore><book id= "1" ><name> Hello </name>< author> John Doe </author><price>80</price></book><book id= "2" ><name> Hello 2</ name><author> John Doe 2</author><price>81</price></book></bookstore>
Java files
Package Cn.lonecloud.xml;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.DocumentBuilderFactory ; import Javax.xml.parsers.parserconfigurationexception;import Org.w3c.dom.document;import org.w3c.dom.Element; Import Org.w3c.dom.node;import Org.w3c.dom.nodelist;public class Domxml {public static void main (string[] args) throws Ex ception {//First set up a Documentbuilderfactory object documentbuilderfactory dbf=documentbuilderfactory.newinstance ();// Establish a Buildfactory object Documentbuilder db=dbf.newdocumentbuilder ();//Get XML File Document Document=db.parse ("Demo.xml");// Gets the root tree of the elementelement e1=document.getdocumentelement ();//Gets the child node of the child element if (e1!=null) {NodeList list=e1.getchildnodes () if (list!=null) {//traverse the book Sub-node for (int i = 0; i < list.getlength (); i++) {Node node=list.item (i); if (node!=null) {NodeList Child=node.getchildnodes (); for (int j = 0; J < Child.getlength (); j + +) {node N=child.item (j);//Gets the property name text if (n.getnodety PE () ==node.element_node) {//Get node name System.out.println (N.getnodename ());//Get this node value syStem.out.println (N.getfirstchild (). Getnodevalue ());//Gets all the text under the value of the node System.out.println (N.gettextcontent ());}}}}}}
DOM parsing XML document in Java