dom4j Quick start

dom4j Quick start

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;
}
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100614.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • mysql磁盘阵列部署_部署磁盘阵列

    mysql磁盘阵列部署_部署磁盘阵列1、mdadm命令用于管理Linux系统中的软件RAID硬盘阵列,格式为mdadm[模式][选项][成员设备名称]常用命令:mdadm-D/dev/md0#md0为自定义设备名,查看详细信息2、mdadm命令的常用参数和作用-a  检测设备名称-n  指定设备数量-l  指定RAID级别-C  创建(阵列卡)-v  显示过程-f   模拟设备损坏-r   …

    2022年6月12日
    40
  • 彻底解决Intellij IDEA中文乱码问题(亲测成功)「建议收藏」

    关于JAVA IDE开发工具,Eclipse系列和Intelli IDEA是大部分公司的主要选择,从开发者的选择角度,Intellij IDEA似乎比Eclipse系列更受欢迎一些。当我们使用Intellij IDEA开发时,我们发现出现中文乱码问题,造成中…

    2022年3月13日
    2.9K
  • C语言优先级 运算符

    C语言优先级 运算符1、最高级:出现同级别运算符时的结合方向是从左往右(下面级别没写结合顺序时,默认是从左往右)。()圆括号[]下标运算符号->指向结构体成员运算符.结构体成员运算符2、第二级:!、~、++、–、-、(类型)、*、&、sizeof。这一级都是单目运算符号,这一级的结合方向是从右向左。比如出现*p++,这时*和++同级别,先算右边,再左边。所以*p+…

    2022年6月16日
    37
  • 安卓手机上超好用的4款C语言IDE(附下载地址)

    安卓手机上超好用的4款C语言IDE(附下载地址)**如果找不到这几款编译器的可以联系我,我发给你QQ:1873564884**电脑有时太麻烦,不方便随时运行测试结果,手机上有不少编译器,子曰:“工欲善其事,必先利其器”。拥有一款好的编译器也是成功的一部分。话不多说让我们来看看。1:C4droid汉化版这款相信大家一定听说过,毕竟我原来也用过,感觉很菜,点击编译后没反应,上网查找说要安装gcc插件,而且要自己要自己找安装目…

    2022年5月6日
    153
  • linux之使用samba实现文件共享

    早期网络想要在不同主机之间共享文件大多要用FTP协议来传输,但FTP协议仅能做到传输文件却不能直接修改对方主机的资料数据,这样确实不太方便,于是便出现了NFS开源文件共享程序,NFS是一个能够将多台L

    2021年12月28日
    52
  • 安捷伦频谱仪n9010a_安捷伦频谱仪LAN设置

    安捷伦频谱仪n9010a_安捷伦频谱仪LAN设置频谱仪操作说明按键输入所测6个频点的中心频率。(注:与步骤8对应,若所测频点为4临频输出,此处频率=第一个频点中心频率+12MHz;若所测频点为6临频输出,此处频率=第一个频点中心频率+20MHz;)20.点击“AMPTD”对应的右侧按键,液晶屏右侧出现一列选项;21.点击“Attenuation”对应的右侧按键,左右旋转按键矩阵中的旋钮键,使得频谱两边的值载噪比最大,此值即为设备的载噪比六.…

    2022年8月11日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号