Application dom4j in Java programming to easily process XML documents

Source: Internet
Author: User
Tags file system xpath

DOM4J is an easy-to-use XML processing tool in the Java platform that uses the Java Collections architecture to provide complete support for DOM,SAX,JAXP.

1. Create a new XML document

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class Users {
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "users" );
Element me = root.addElement( "user" )
.addAttribute( "userid", "sucode" )
.addAttribute( "username", "Eric Yu" )
.addText( "myself" );
Element me = root.addElement( "user" )
.addAttribute( "userid", "scottl" )
.addAttribute( "username", "Scott Long" )
.addText( "FreeBSD leader" );
return document;
}
}

The above code creates the following XML document:

<users>
<user userid="sucode" username="Eric Yu">myself</user>
<user userid="scottl" username="Scott Long">FreeBSD leader</user>
</users>

2.XML conversion between a document and a string

One of the dom4j features that individuals prefer is that it provides a very easy way to convert an XML document into an XML-formatted string. Because Document,element,attribute inherits the node interface, they all provide a asxml () method that returns the XML format description of the node.

Document document = (new Users ()). CreateDocument ();

String text = Document.asxml ();

It is also easy to convert an XML string to document:

Document doc = documenthelper.parsetext (text);

3. Fast Traversal

If you need to process a large XML document, creating a iterator object for Each loop will incur a significant overhead. It is recommended to use fast traversal at this time (fast looping):

public void treeWalk(Document document) {
treeWalk( document.getRootElement() );
}
public void treeWalk(Element element) {
for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
Node node = element.node(i);
if ( node instanceof Element ) {
treeWalk( (Element) node );
}
else {
// 具体业务代码
}
}
}

4. Using XPath

In dom4j, XPath can work on a document or on any node.

// 返回users下的所有user节点
List userlist = document.selectNodes("//users/user");
//返回users下的userid为sucode的user节点
User me = (Element)document.selectSingleNode("//users/user[@userid=&#39;sucode&#39;]");

selectSingleNode returns the first node that meets the criteria, and if more than one node matches, the subsequent nodes are ignored

5. Write XML document to file

We often keep XML documents in the form of files. DOM4J provides a very intuitive way to write XML documents to the file system:

FileWriter out = new FileWriter ("Users.xml");

document.write (out);

You can also specify the format of the output by XmlWriter:

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class DOMTest {
public void write(Document document) throws IOException {
// 创建XMLWriter对象,目标文件users.xml,使用PrettyPrint格式
XMLWriter writer = new XMLWriter(new FileWriter("users.xml"),
OutputFormat.createPrettyPrint());
// 写文档
writer.write(document);
// 关闭writer
writer.close();
}
}

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.