Using DOM4J to parse XML in Java (sample code) _java

Source: Internet
Author: User
Tags gettext

Although there are already two standard parsing methods for DOM and sax in Java

But it is not easy to operate, for a beginner like me, part of the code is living nausea

To this end, the great third party development team developed jdom and DOM4J tools

Given the current trend, we are here to talk about the basic usage of dom4j, not involving complex operations such as recursion.

DOM4J is a lot of use, the official online example is a little obscure, here is not written

First we need to create an XML document and then parse it

XML document:

Copy Code code as follows:

<?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>
</book>
</books>

Example One: Parsing XML in list form
Copy Code code as follows:

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 in case
/*list<attribute> attributelist = Child.attributes ();
for (Attribute attr:attributelist) {
System.out.println (Attr.getname () + ":" + attr.getvalue ());
}*/

Given the name of the property
SYSTEM.OUT.PRINTLN ("ID:" + child.attributevalue ("id"));

Unknown child element name in case
/*list<element> elementlist = child.elements ();
for (Element ele:elementlist) {
System.out.println (Ele.getname () + ":" + Ele.gettext ());
}
System.out.println ();

In the case of a known child element name
System.out.println ("title" + Child.elementtext ("title"));
System.out.println ("Author" + Child.elementtext ("author"));
This line is for the sake of formatting beauty.
System.out.println ();
}
}

}


Example Two: parsing XML using a iterator iterator
Copy Code code as follows:

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 property name in case
/*iterator Attrit = Element.attributeiterator ();
while (Attrit.hasnext ()) {
Attribute A = (attribute) attrit.next ();
System.out.println (A.getvalue ());
}*/

Given the name of the property
SYSTEM.OUT.PRINTLN ("ID:" + element.attributevalue ("id"));

Unknown element name in case
/*iterator Eleit = Element.elementiterator ();
while (Eleit.hasnext ()) {
Element e = (Element) Eleit.next ();
System.out.println (E.getname () + ":" + E.gettext ());
}
System.out.println ();

In the case of known element names
System.out.println ("title:" + element.elementtext ("title"));
System.out.println ("Author:" + element.elementtext ("author"));
System.out.println ();
}
}
}


Run Result:

Example three: Creating an XML document and outputting it to a file

Copy Code code as follows:

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.createdocument ();
Add root node
Element books = doc.addelement ("books");
Adding child elements
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");

To add a property to a child node
Book1.addattribute ("id", "001");
Add content to an element
Title1.settext ("Harry Potter");
Author1.settext ("J K. Rowling");

Book2.addattribute ("id", "002");
Title2.settext ("Learning XML");
Author2.settext ("Erik T. Ray");

Instantiating an output Format object
OutputFormat format = Outputformat.createprettyprint ();
Set Output encoding
Format.setencoding ("UTF-8");
Create a file object to write to
File File = new file ("D:" + file.separator + "books.xml");
Generates a XmlWriter object in which the parameters in the constructor are the file stream and format required for output
XMLWriter writer = new XMLWriter (new FileOutputStream (file), format);
Start writing, the Write method contains the Document object created above
Writer.write (DOC);
}
}


Run Result:

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.