DOM parsing XML document in Java

Source: Internet
Author: User

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

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.