Parsing XML using DOM4J in Java

Source: Internet
Author: User
Tags gettext

Creating an XML document and outputting it to a file

Import Java.io.file;import Java.io.FileOutputStream; Import Org.dom4j.document;import Org.dom4j.documenthelper;import Org.dom4j.element;import  Org.dom4j.io.outputformat;import Org.dom4j.io.XMLWriter; public class Demo {public static void main (string[] args) throws Exception {Document doc = Documenthelper.crea        Tedocument ();        Add the root node Element books = Doc.addelement ("books");        add element Book1 = books.addelement ("book");        Element title1 = book1.addelement ("title");                 Element Author1 = book1.addelement ("author");        Element Book2 = books.addelement ("book");        Element title2 = book2.addelement ("title");                 Element Author2 = book2.addelement ("author");        Add attribute Book1.addattribute ("id", "001") for child nodes;        Add content to the element Title1.settext ("Harry Potter");                 Author1.settext ("J K. Rowling");        Book2.addattribute ("id", "002");        Title2.settext ("Learning XML"); Author2.settExt ("Erik T. Ray");        Instantiate the output format object OutputFormat format = Outputformat.createprettyprint ();        Set output encoding format.setencoding ("UTF-8");        Create file object to write File File = new file ("D:" + file.separator + "books.xml");        Generate the XMLWriter object, the parameters in the constructor are the file stream and format that needs to be output XMLWriter writer = new XMLWriter (new FileOutputStream (file), format);    Start writing, the Write method contains the Document object created above Writer.write (DOC);   }}

After running, a books.xml is generated under the D-disk

Parsing XML using the iterator iterator

The XML document is as follows:

<?XML version= "1.0" encoding= "UTF-8"?> <Books>    < BookID= "001">       <title>Harry Potter</title>       <author>J K. Rowling</author>    </ Book>    < BookID= "002">       <title>Learning XML</title>       <author>Erik T. Ray</author>    </ Book> </Books> 

ImportJava.io.File;ImportJava.util.Iterator;ImportOrg.dom4j.Attribute;Importorg.dom4j.Document;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader;  Public classDemo { Public Static voidMain (string[] args)throwsException {Saxreader reader=NewSaxreader (); Document Document= Reader.read (NewFile ("books.xml")); Element Root=document.getrootelement (); Iterator it=Root.elementiterator ();  while(It.hasnext ()) {element element=(Element) it.next (); //Unknown attribute name case            /*Iterator Attrit = Element.attributeiterator ();                while (Attrit.hasnext ()) {Attribute a = (Attribute) attrit.next ();            System.out.println (A.getvalue ()); }*/                         //given the name of the propertySYSTEM.OUT.PRINTLN ("ID:" + element.attributevalue ("id"))); //unknown element name Case            /*Iterator Eleit = Element.elementiterator ();                while (Eleit.hasnext ()) {Element E = (Element) Eleit.next ();            System.out.println (E.getname () + ":" + E.gettext ()); } System.out.println ();*/                         //given the name of the elementSystem.out.println ("title:" + element.elementtext ("title"))); System.out.println ("Author:" + element.elementtext ("Author"));        System.out.println (); }    }}

Operation Result:

Parse the XML in the form list

ImportJava.io.File;Importjava.util.List;ImportOrg.dom4j.Attribute;Importorg.dom4j.Document;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader;  Public classDemo { Public Static voidMain (string[] args)throwsException {Saxreader reader=NewSaxreader (); File File=NewFile ("books.xml"); Document Document=reader.read (file); Element Root=document.getrootelement (); List<Element> childelements =root.elements ();  for(Element child:childelements) {//Unknown attribute name in the case of            /*list<attribute> attributelist = Child.attributes ();            for (Attribute attr:attributelist) {System.out.println (Attr.getname () + ":" + attr.getvalue ()); }*/                         //In case of known attribute nameSYSTEM.OUT.PRINTLN ("ID:" + child.attributevalue ("id"))); //Unknown child element name Case            /*list<element> elementlist = child.elements ();            for (Element ele:elementlist) {System.out.println (Ele.getname () + ":" + Ele.gettext ()); } System.out.println ();*/                         //in the case where the child element name is knownSystem.out.println ("title" + Child.elementtext ("title"))); System.out.println ("Author" + Child.elementtext ("Author")); //This line is for the sake of formatting beautiful and existsSystem.out.println (); }    } }

Parsing XML using DOM4J 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.