DOM4J Read XML file--java

Source: Internet
Author: User

A few days ago, with Dom4j wrote three versions of the read XML file, now share the next.

First version:XML:

<?xml version= "1.0" encoding= "UTF-8"? ><do-config><do path= "User/adduser" type= " Userpackage.userservlet "><forward name=" Success ">addsuccess.jsp</forward></do></ Do-config>

dom4j reads this XML code as follows:

public static void Read () {try {//Read and parse XML document//Saxreader is a pipeline that reads the XML file out of a stream saxreader reader = new Saxreader ();//Us Er.hbm.xml represents the XML document you want to parse inputstream in = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (" Newfile.xml ");D ocument doc = Reader.read (in);//Gets the root node element rootelt = Doc.getrootelement (); Get the Do node element doelement = Rootelt.element ("Do"); Gets the property under the Do node, string path=doelement.attributevalue ("path"); String type=doelement.attributevalue ("type");//Get forward node element forwardelement =doelement.element ("forward");// Gets the attribute and literal value in the Forward node, string name=forwardelement.attributevalue ("name"); String Value=forwardelement.gettext (); SYSTEM.OUT.PRINTLN ("root node:" + Rootelt.getname ()); Get the root node name System.out.println ("Do Node:" +doelement.getname ()); System.out.println (the properties of the Do node, path and type are: "+path+", "+type", respectively); System.out.println ("Forward node:" +forwardelement.getname ()); System.out.println ("Forward node property name is:" +name); System.out.println (The text value of the forward node is: "+value);} catch (Documentexception e) {e.printsTacktrace ();} catch (Exception e) {e.printstacktrace ();}}

The output results are as follows:


thinking:

This XML file is relatively simple, under the root node there are only different two-level nodes, three-level nodes, no duplicate child nodes, that is, there are not several same two-level nodes do or not several of the same three-level node forward. At the same time, when reading, open to the node, what does it mean? That is, read the XML in the code to see the nodes in the XML file. Since there are these problems, how should we solve them? Look at the next version.

A second version:The XML file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><do-config><do path= "User/adduser" type= " Userpackage.userservlet "><forward name=" Success ">addsuccess.jsp</forward><forward name=" Error " >Adderror.jsp</forward></do></do-config>

dom4j Read the XML file code as follows:

public static void Readstringxml () {//Document DOC = Null;try {//Read and parse the XML document//Saxreader is a pipeline that reads the XML file in a flow mode Saxreade R reader = new Saxreader (); User.hbm.xml represents the XML document you want to parse inputstream in = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (" Newfile.xml ");D ocument doc = Reader.read (in); Element Rootelt = Doc.getrootelement (); Gets the root node System.out.println ("root node:" + Rootelt.getname ()); Get the name of the root node for (int i = 0; i < Rootelt.nodecount (); i++) {Node node = Rootelt.node (i); if (node instanceof Element) {Ele ment elementtemp = (Element) node; System.out.println ("Level Two node do:" + node.getname ()); Get the name of the first level two node do//gets the value of the type and path property of level Two node do (Iterator iter = Elementtemp.attributeiterator (); Iter.hasnext ();) {Attribute item = (Attribute) iter.next (); System.out.println ("Level Two node do:" + item.getname () + "=" + Item.getvalue ()); Get the two-level node path and type}//to get the two-level node below the child node forward (three-level node) for (Iterator Iterroot2 = Elementtemp.elementiterator (); Iterroot2.hasnext ();) {element root22 = (Element) ITERROOT2.NExt (); Get a Level Two node System.out.println ("Level Three node Forward:" + root22.getname ()); System.out.println ("Value of level three node forward:" + root22.gettext ()); Gets the value of the forward list attrlist = Root22.attributes (); Gets the properties of a level three node//traverse gets the properties of a level three node for (Iterator iter = Attrlist.iterator (); Iter.hasnext ();) {Attribute item = (Attribute) iter.next (); System.out.println ("attribute of level three node forward:" + item.getname () + "for" + Item.getvalue ());}}}} catch (Documentexception e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ()}}

The results appear as follows:


thinking:

This method uses iterations to solve the problem of having the same node name in the XML file that is being read, looking at the code that reads the XML file separately, without seeing the node objects and attributes in the XML file. But it also has a new problem, if the root node is no longer limited to its child nodes up to three levels, if the node has four levels, five levels, and even more, what should be done? How to solve this problem? See a third version

Third version:XML

<?xml version= "1.0" encoding= "UTF-8"? ><do-config><do path= "User/adduser" type= " Userpackage.userservlet "><forward name=" Success ">addsuccess.jsp</forward><forward name=" Error " >Adderror.jsp</forward></do> <do path= "User/deluser" type= "Userpackage.deluserservlet" >< Forward name= "Error" ><current>zhudan.jsp</current></forward></do> </do-config>

dom4j reads the XML code as follows:

public static void ReadXml () {Saxreader reader = new Saxreader ();//User.hbm.xml represents the XML document you want to parse inputstream in = Thread.curre Ntthread (). Getcontextclassloader (). getResourceAsStream ("Newfile.xml"); try {Document doc = Reader.read (in); Element root = Doc.getrootelement (); Gets the root node list<element> list = new arraylist<element> (); List.add (root); while (list = null) {element element = N Ull Element ele = null;iterator ite = List.iterator (); if (Ite.hasnext ()) {ele = (Element) ite.next (); Ite.remove ();} if (ele! = null) {for (Iterator i = Ele.elementiterator (); (i! = null) && (I.hasnext ());) {element = (element) i.next (); List.add (element); if (element! = null) {System.out.println (Element.getname () + ":" + elemen T.getpath () + "--" + element.gettext ()); for (Iterator iter = Element.attributeiterator (); Iter.hasnext ();) {Attribute item = (Attribute) iter.next (); System.out.println (Item.getname () + "for" + Item.getvalue ());}}}}} catch (Documentexception e) {e.printstacktrace ();}}

The results of the operation are as follows:


thinking:

This method reads the XML file, and I don't have to worry about what the contents of my XML file are, how many nodes there are, how many node attributes I only care about the name of the XML file.

Summary:

These three versions of the code about DOM4J read XML file, in fact, it is also my thinking process, through the extension of others to expand their own, positive thinking, will bring a different harvest.





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.