parsing XML files in Java using dom4j

Source: Internet
Author: User
Tags gettext

I. Preface

In the recent development of the use of dom4j to parse XML files, previously heard to parse the XML file of several standard ways, but never applied, so you can search in Google dmo4j parse XML file, learn how to parse XML dom4j the specific operation.

Two. Code details

dom4j is a plug-in developed by a third-party development group, so when we use DOM4JF we are going to download the dom4j corresponding version of the jar import in our project.

1) XML file:

<?xml version= "1.0" encoding= "UTF-8"?> <books>    <book id= "001" >       <title>harry Potter </title>       <author>j K. rowling</author>    </book>    <book id= "002" >       <title>learning xml</title>       <author>erik T. ray</author>    

Example one: Parsing XML in a list of lists

Import Java.io.file;import java.util.List;   Import Org.dom4j.attribute;import org.dom4j.document;import org.dom4j.element;import org.dom4j.io.SAXReader; public class Demo {public static void main (string[] args) throws Exception {Saxreader reader = new Saxreader (        );        File File = new file ("books.xml");        Document document = Reader.read (file);        Element root = Document.getrootelement ();        list<element> childelements = root.elements (); for (Element child:childelements) {//unknown property name/*list<attribute> attributelist = Child.attri            Butes ();            for (Attribute attr:attributelist) {System.out.println (Attr.getname () + ":" + attr.getvalue ());                         }*///Known attribute name SYSTEM.OUT.PRINTLN ("ID:" + child.attributevalue ("id"));            Unknown child element name in case of/*list<element> elementlist = Child.elements (); for (Element ele:elementlist) {System.out.println (Ele.getname () + ":" + Ele.gettext ()); } System.out.println (); *///System.out.println ("title" + Child.el in case the child element name is known)            Ementtext ("title"));            System.out.println ("Author" + Child.elementtext ("author"));        This line is for the sake of formatting beautiful and existence System.out.println (); }    } }

Example two: Parsing XML using a iterator iterator

Import Java.io.file;import java.util.Iterator;   Import Org.dom4j.attribute;import org.dom4j.document;import org.dom4j.element;import org.dom4j.io.SAXReader; public class Demo {public static void main (string[] args) throws Exception {Saxreader reader = new Saxreader ()        ;        Document document = Reader.read (new File ("books.xml"));                 Element root = Document.getrootelement ();        Iterator it = Root.elementiterator ();                         while (It.hasnext ()) {element element = (Element) It.next ();            Unknown attribute name in case/*iterator Attrit = Element.attributeiterator ();                while (Attrit.hasnext ()) {Attribute a = (Attribute) attrit.next ();            System.out.println (A.getvalue ());                         }*///Known attribute name Case SYSTEM.OUT.PRINTLN ("ID:" + element.attributevalue ("id"));            Unknown element name in case of/*iterator Eleit = Element.elementiterator (); while (ELeit.hasnext ()) {element e = (Element) Eleit.next ();            System.out.println (E.getname () + ":" + E.gettext ()); } System.out.println (); *///known element name System.out.println ("title:" + element.)            Elementtext ("title"));            System.out.println ("Author:" + element.elementtext ("author"));        System.out.println (); }    }}

Operation Result:

example three: 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); }}

Operation Result:

 

parsing XML files in Java using dom4j

Related Article

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.