Dom4j quick start guide
Parsing XML
Using Iterators
Powerful Navigation with XPath
Fast Looping
Creating a new XML document
Writing a document to a file
Converting to and from Strings
Styling a Document with XSLT
Parsing XML
One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in
dom4j . The following code demonstrates how to this.
import java.net.URL; import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class Foo { public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; }
}
Using Iterators
A document can be navigated using a variety of methods that return standard Java Iterators. For example
public void bar(Document document) throws DocumentException { Element root = document.getRootElement(); // iterate through child elements of root
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next(); // do something
} // iterate through child elements of root with element name "foo"
for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) { Element foo = (Element) i.next(); // do something
} // iterate through attributes of root for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { Attribute attribute = (Attribute) i.next(); // do something }
}
Powerful Navigation with XPath
In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.
public void bar(Document document) { List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" ); }
For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.
public void findLinks(Document document) throws DocumentException { List list = document.selectNodes( "//a/@href" ); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); } }
If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.
Fast Looping
If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example
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 { // do something.... } } }
Creating a new XML document
Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.
import org.dom4j.Document;
import org.dom4j.DocumentHelper; import org.dom4j.Element; public class Foo { public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Bob" ) .addAttribute( "location", "US" )
.addText( "Bob McWhirter" ); return document; } }
Writing a document to a file
A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.
FileWriter out = new FileWriter( "foo.xml" ); document.write( out );
If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.
import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class Foo { public void write(Document document) throws IOException { // lets write to a file XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) ); writer.write( document ); writer.close(); // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter( System.out, format ); writer.write( document ); // Compact format to System.out format = OutputFormat.createCompactFormat(); writer = new XMLWriter( System.out, format ); writer.write( document ); } }
Converting to and from Strings
If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.
Document document = ...; String text = document.asXML();
If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()
String text = "<person> <name>James</name> </person>"; Document document = DocumentHelper.parseText(text)
Styling a Document with XSLT
Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.
import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public class Foo { public Document styleDocument( Document document, String stylesheet ) throws Exception {
// load the transformer using JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer( new StreamSource( stylesheet ) ); // now lets style the given document DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
transformer.transform( source, result ); // return the transformed document Document transformedDoc = result.getDocument(); return transformedDoc; } }
Dom4j quick start guide的更多相关文章
- SlickUpload Quick Start Guide
Quick Start Guide The SlickUpload quick start demonstrates how to install SlickUpload in a new or ex ...
- RF《Quick Start Guide》操作总结
这篇文章之所以会给整理出来,是因为学了一个季度的RF后,再去看官网的这个文档,感触破多,最大的感触还是觉得自己走了不少弯路,还有些是学习方法上的弯路.在未查看这类官网文档之前,更多的是看其他各种人的博 ...
- QUICK START GUIDE
QUICK START GUIDE This page is a guide aimed at helping anyone set up a cheap radio scanner based on ...
- Akka Stream文档翻译:Quick Start Guide: Reactive Tweets
Quick Start Guide: Reactive Tweets 快速入门指南: Reactive Tweets (reactive tweets 大概可以理解为“响应式推文”,在此可以测试下GF ...
- RobotFramework 官方demo Quick Start Guide rst配置文件分析
RobotFramework官方demo Quick Start Guide rst配置文件分析 by:授客 QQ:1033553122 博客:http://blog.sina.com.c ...
- RobotFramework RobotFramework官方demo Quick Start Guide浅析
RobotFramework官方demo Quick Start Guide浅析 by:授客 QQ:1033553122 博客:http://blog.sina.com.cn/ishouk ...
- pax3 quick start guide
pax3 quick start guide 外观图: 配置:1 * pax3 主机:2 * 吸嘴(一个平的,一个凸的):2 * 底盖(一个烟草的,一个烟膏的):3 * 过滤片:1 * USB充:1 ...
- quick start guide for XMEGA ADC
This is the quick start guide for the Analog to Digital Converter (ADC), with step-by-step instructi ...
- [摘录]quarts:Quartz Quick Start Guide
(Primarily authored by Dafydd James) Welcome to the QuickStart guide for Quartz. As you read this gu ...
随机推荐
- 【BZOJ1923】[Sdoi2010]外星千足虫 高斯消元
[BZOJ1923][Sdoi2010]外星千足虫 Description Input 第一行是两个正整数 N, M. 接下来 M行,按顺序给出 Charles 这M次使用“点足机”的统计结果.每行 ...
- The E-pang Palace(暴力几何)
//暴力的几何题,问,n个点可以组成的矩形,不相交,可包含的情况下,最大的面积,还有就是边一定与 x y 轴平行,所以比较简单了 //暴力遍历对角线,搜出所有可能的矩形,然后二重循环所有矩形,判断一下 ...
- SpringBoot自带热加载开发工具
SpringBoot自带热加载开发工具 maven配置: <!-- SpringBoot自带热加载开发工具 --> <dependency> <groupId>or ...
- C# new和override区别(转)
override 1. override是派生类用来重写基类中方法的: 2. override不能重写非虚方法和静态方法: 3. override只能重写用virtual.abstract.overr ...
- python系列十四:Python3 文件
#!/usr/bin/python #Python3 文件 from urllib import requestimport pprint,pickle'''读和写文件open() 将会返回一个 fi ...
- h5-localStorage实现缓存ajax请求数据
使用背景:要实现每次鼠标hover“能力雷达”,则显示能力雷达图(通过ajax请求数据实现雷达图数据显示),所以每次hover都去请求ajax会影响性能,因此这里要用到本地缓存. 实现: 此处是通过传 ...
- 如何枚举 Windows 顶级桌面窗口?
bool is_top_level_window(HWND hwnd) { if (!IsWindow(hwnd)) return false; DWORD dw_style = GetWindowL ...
- Python3.6全栈开发实例[016]
16.电影打分:程序先给出几个目前正在上映的电影列表. 由用户给每个电影投票.最终将该用户投票信息公布出来 lst = ['北京遇上西雅图', '解救吴先生', '美国往事', '西西里的美丽传说'] ...
- 我的Android进阶之旅------>Android关于dp(dip)、sp转px的工具类
下面是一个工具类,提供了dp.sp.px之间相互转化的方法. import android.content.Context; /** * dp.sp 转换为 px 的工具类<br> * & ...
- git原理:.git隐藏文件夹介绍
config 定义项目特有的配置选项description 仅供git web程序使用info/ 包含一个全局排除文件(exclude文件),用于配置不在.gitignore中的忽略模式hooks/ ...