XML series: (6) XML parsing-dom4j Dom parsing method reading XML

Source: Internet
Author: User
Tags list of attributes xml parser

Dom4j tool, is unofficial, not in the JDK.

Steps to use:

1) Import the core package of dom4j. Dom4j-1.6.1.jar

2) write the code dom4j read the XML file


Animals.xml

<?xml version= "1.0" encoding= "UTF-8"? ><animals><cat id= "c001" name= "Meow Mew" ><Home> Mars 


1. Read XML


1.1. Get the Document Object

Package Com.rk.xml.f_dom4j_read;import Java.io.file;import Org.dom4j.document;import org.dom4j.DocumentException; Import org.dom4j.io.saxreader;/** * First DOM4J Read XML document example * Get Document Object * @author RK */public class Demo01{public static Voi D main (string[] args) {try{//1. Create an XML parser object Saxreader reader = new Saxreader ();//2. Read XML document, return Document Object doc = Reader.read (New File ("./src/animals.xml")); System.out.println (DOC);} catch (Documentexception e) {e.printstacktrace (); throw new RuntimeException (e);}}


1.2. read XML file contents: node, tag, attribute, text

package com.rk.xml.f_dom4j_read;import java.util.list;import java.io.file;import  java.util.iterator;import org.dom4j.document;import org.dom4j.documentexception;import  org.dom4j.element;import org.dom4j.node;import org.dom4j.attribute;import  org.dom4j.io.saxreader;import org.junit.test;/** *  second dom4j reads XML file contents  *  nodes  *   Tags  *  properties  *  text  *  @author  rk * */public class demo02 {/** *  Get the node  * 1, get the root element document.getrootelement ()  * 2 through the document file, get all the child nodes under the tag element  branch.nodeiterator ()  * 3, the name of the acquired node, type: Node.getname (),  node.getnodetype (),  Node.getnodetypename ()  */@Testpublic  void testnode () {try{//1. read XML document, return Document Object Saxreader  reader = new saxreader ();D Ocument doc = reader.read (New File ("./src/ Products.xml "));//2, get root tag element rootelement = doc.getrooteLement ();//3, traverse all nodes of the document Getchildnodes (rootelement);} catch  (documentexception e) {e.printstacktrace ();}} Private void getchildnodes (Element elem) {//nodeiterator:  gets all child node objects under the current node (nodes that do not contain grandchildren) @ Suppresswarnings ("Unchecked") iterator<node> it = elem.nodeiterator (); while (It.hasNext ()) { Node node = it.next (); System.out.println (Node.getname ()  +  "= = ="  + node.getnodetype ()  +  "= = ="  +  node.getnodetypename ());//determine if the Label element if (node instanceof element) {getchildnodes (Element) node);}} /** *  get the label  * 1, get a specific label  element.element (string name)  :  Get the first sub-label of the specified name under the current tab &NBSP;*&NBSP;2, get all sub-tags  element.elementiterator (string name):   Gets all the child tags of the specified name under the current label  */@Testpublic  void testelement ()  throws exception{//1. Read the XML document, Returns the Document object Saxreader reader = new saxreader ();D Ocument doc = reader.read ( New fIle ("./src/animals.xml"));//2. Get root Tag System.out.println ("===================================2"); Element rootelement = doc.getrootelement ();//Get node-related information string name =  Rootelement.getname ();//Get Node name Short type = rootelement.getnodetype ();//Get node type string  Typename = rootelement.getnodetypename ();//Gets the node type name System.out.println (name +  "\ T"  +  type +  "\ T"  + typename)//3. Gets the first sub-label of the specified name under the current label System.out.println ("================== =================3 "); Element productelement = rootelement.element ("Dog"); System.out.println (Productelement.getname ())//4. Gets all the child tags of the specified name under the current label System.out.println ("======================== ===========4 "), @SuppressWarnings (" unchecked ") iterator<element> it =   Rootelement.elementiterator ("Cat"), while (It.hasnext ()) {element elem = it.next (); System.out.println (Elem.getname ());} 5. Get all the sub-tags under the current tab SYSTEM.OUT.PRINTLN ("===================================5 "), @SuppressWarnings (" Unchecked ") list<element> list = rootelement.elements (); /Traversal list Method//1) traditional for loop   2) enhanced for loop  3) iterator//for (Int i=0;i<list.size (); i++)//{// System.out.println (List.get (i). GetName ());//}//for (element elem : list)//{//system.out.println ( Elem.getname ());//}iterator<element> iterator = list.iterator (); while (Iterator.hasNext ()) {Element elem = iterator.next (); System.out.println (Elem.getname ());} 6, to obtain a deeper level of the label (method can only be a layer of access) System.out.println ("===================================6"); Element nameelement = rootelement.element ("Dog"). Element ("Home"); System.out.println (Nameelement.getname ()); System.out.println (Nameelement.gettext ()); System.out.println (Nameelement.getpath ()); System.out.println (Nameelement.getuniquepath ());} /** *  gets the property  * 1, gets a specific property  * 2, gets all the attributes under the tag element  */@Testpublic  void  Testattribute ()  throws exception{//reads an XML document, returns the File Object Saxreader reader = new saxreader ();D ocument doc =  Reader.read (New file ("./src/animals.xml")); Element rootelement = doc.getrootelement ();//Gets the property: (The Label object where the property is first obtained, and then the property can be obtained)//1. Get the Tag object element  dogelement = rootelement.element ("Dog");//2. Gets the attribute//2.1   gets the property value of the specified name System.out.println ( "===================================2.1"); String idvalue = dogelement.attributevalue ("id"); System.out.println (idvalue);//2.2  Gets the Property object with the specified property name System.out.println ("===================================2.2 "); Attribute idattr = dogelement.attribute ("name");//getname:  property name      GetValue: Attribute value System.out.println (idattr.getname ()  +  "="  + idattr.getvalue ());//2.3  Get all Property objects, return the list collection System.out.println ("===================================2.3"); @SuppressWarnings ("Unchecked") List<attribute> list = dogelement.attributes ();//Traverse property for (Attribute&nbsP;attr : list) {System.out.println (Attr.getname ()  +  "="  + attr.getvalue ());} 2.4  gets all the property objects, returns the iterator System.out.println ("===================================2.4"); @SuppressWarnings (" Unchecked ") iterator<attribute> iterator = rootelement.element (" Cat "). AttributeIterator (); while (Iterator.hasnext ()) {attribute attr = iterator.next (); System.out.println (Attr.getname ()  +  "="  + attr.getvalue ());}} /** *  Gets the text  * 1, gets the text of the current LABEL element Element.gettext ()  * 2, gets the text of the child label Element Element.elementtext ( String name)  */@Testpublic  void testtext ()  throws exception{//read the XML document, Returns the Document object Saxreader reader = new saxreader ();D Ocument doc = reader.read ( New file ("./src/animals.xml")); Element rootelement = doc.getrootelement ();//note:  spaces and line breaks are also XML content string content =  rootelement.gettext (); System.out.println ("==start=="  + content +  "==end==");//Get the text (get the label first, then get the text on the label) element borndateelement =  Rootelement.element ("Cat"). Element ("Borndate");//1.  get text string text =  Borndateelement.gettext (); The text of System.out.println (Borndateelement.getname ()  +  "element is"  + text);//2.  Gets the text content of the specified sub-label name String text2 = rootelement.element ("Dog"). Elementtext ("Home"); System.out.println (Text2);}}



1.3. Practice-Read the contents of the XML document in full

package com.rk.xml.f_dom4j_read;import java.io.file;import java.util.iterator;import  org.dom4j.document;import org.dom4j.node;import org.dom4j.element;import org.dom4j.attribute; import org.dom4j.io.saxreader;/** *  exercise-Full Read XML document content  *  @author  rk * */ Public class demo03{public static void main (String[] args)  throws  exception{//read XML document Saxreader reader = new saxreader ();D ocument doc =  Reader.read (New file ("./src/animals.xml"));//Read root tag element rootelement = doc.getrootelement (); Stringbuilder sb = new stringbuilder (); Getchildnodes (ROOTELEMENT,SB); System.out.println (Sb.tostring ());} /** *  gets all child nodes of the current label  */private static void getchildnodes (element  CURRENTELEMENT,&NBSP;STRINGBUILDER&NBSP;SB) {string name = currentelement.getname ();// Start label Startsb.append ("<" +name);//Get the list of attributes for the label @suppresswarnings ("Unchecked") iterator<attribute> iterator =  Currentelement.attributeiterator (); while (Iterator.hasnext ()) {attribute attr = iterator.next (); String attrname = attr.getname (); String attrvalue = attr.getvalue (); Sb.append (" "  + attrName +  "=\" "  + attrValue +  "\" ");} Start tag endsb.append (">");//Get child node @suppresswarnings ("Unchecked") iterator<node> it =  Currentelement.nodeiterator (); while (It.hasnext ()) {node node = it.next (); short type =  node.getnodetype (); if (Type == node.element_node) {getchildnodes (ELEMENT) NODE,&NBSP;SB);} Else if (Type == node.text_node) {sb.append (Node.gettext ());} else{//other cases, do not do the processing}}//end tag sb.append ("</"  + name +  ">");}}




2. Mind Mapping

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/80/0F/wKioL1c2J2mQaTfAAAHmv1_GZM0598.png "title=" Dom4j.png "alt=" Wkiol1c2j2mqatfaaahmv1_gzm0598.png "/>





XML series: (6) XML parsing-dom4j 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.