DOM4J 使用简介

Dom4j 使用简介

作者:冰云<spanlang=en-us style="font-family:&quot;Courier New&quot;;color:navy"> icecloud(AT)sina.com

时间:<spanlang=en-us style="font-family:&quot;Courier New&quot;;color:navy">2003.12.15

 

版权声明:

本文由冰云完成,首发于CSDN,未经许可,不得使用于任何商业用途。

文中代码部分引用自DOM4J文档。

欢迎转载,但请保持文章及版权声明完整。

如需联络请发邮件:icecloud(AT)sina.com

 

    DOM4J<spanstyle='font-family:宋体'>是dom4j.org<spanstyle='font-family:宋体'>出品的一个开源XML<spanstyle='font-family:宋体'>解析包,它的网站中这样定义:

Dom4j<spanlang=en-us style="font-family:&quot;Courier New&quot;;color:navy"> is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.

Dom4j<spanstyle='font-family:宋体;color:navy'>是一个易用的、开源的库,用于XML<spanstyle='font-family:宋体;color:navy'>,XPath<spanstyle='font-family:宋体;color:navy'>和XSLT<spanstyle='font-family:宋体;color:navy'>。它应用于Java<spanstyle='font-family:宋体;color:navy'>平台,采用了Java<spanstyle='font-family:宋体;color:navy'>集合框架并完全支持DOM<spanstyle='font-family:宋体;color:navy'>,SAX<spanstyle='font-family:宋体;color:navy'>和JAXP<spanstyle='font-family:宋体;color:navy'>。

DOM4J使用起来非常简单。只要你了解基本的<spanlang=en-us style="font-family:&quot;Courier New&quot;">XML-DOM<spanstyle='font-family:宋体'>模型,就能使用。然而他自己带的指南只有短短一页(html),不过说的到挺全。国内的中文资料很少。因而俺写这个短小的教程方便大家使用,这篇文章仅谈及基本的用法,如需深入的使用,请<spanlang=en-us style="font-family:&quot;Courier New&quot;">……自己摸索或查找别的资料。

之前看过<spanlang=en-us style="font-family:&quot;Courier New&quot;">IBM developer<spanstyle='font-family:宋体'>社区的文章(参见附录),提到一些XML解析包的性能比较,其中<spanlang=en-us style="font-family:&quot;Courier New&quot;">DOM4J<spanstyle='font-family:宋体'>的性能非常出色,在多项测试中名列前茅。(事实上DOM4J的官方文档中也引用了这个比较)所以这次的项目中我采用了<spanlang=en-us style="font-family:&quot;Courier New&quot;">DOM4J<spanstyle='font-family:宋体'>作为XML<spanstyle='font-family:宋体'>解析工具。

在国内比较流行的是使用<spanlang=en-us style="font-family:&quot;Courier New&quot;">JDOM作为解析器,两者各擅其长,但DOM4J<spanstyle='font-family:宋体'>最大的特色是使用大量的接口,这也是它被认为比JDOM灵活的主要原因。大师不是说过么,<spanlang=en-us style="font-family:&quot;Courier New&quot;">“面向接口编程<spanstyle='font-family:宋体'>。目前使用DOM4J<spanstyle='font-family:宋体'>的已经越来越多。如果你善于使用JDOM,不妨继续用下去,只看看本篇文章作为了解与比较,如果你正要采用一种解析器,不如就用<spanlang=en-us style="font-family:&quot;Courier New&quot;">DOM4J<spanstyle='font-family:宋体'>吧。

它的主要接口都在<spanlang=en-us style="font-family:&quot;Courier New&quot;">org.dom4j<spanstyle='font-family:宋体'>这个包里定义:

Attribute

Attribute定义了XML的属性

Branch

Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为,

CDATA

CDATA 定义了XML CDATA 区域

CharacterData

CharacterData是一个标识借口,标识基于字符的节点。如CDATAComment, Text.

Comment

Comment 定义了XML注释的行为

Document

定义了XML文档

DocumentType

DocumentType 定义XML DOCTYPE声明

Element

Element定义XML 元素

ElementHandler

ElementHandler定义了 Element 对象的处理器

ElementPath

ElementHandler 使用,用于取得当前正在处理的路径层次信息

Entity

Entity定义 XML entity

Node

Node为所有的dom4jXML节点定义了多态行为

NodeFilter

NodeFilter 定义了在dom4j节点中产生的一个滤镜或谓词的行为(predicate

ProcessingInstruction

ProcessingInstruction 定义 XML 处理指令.

Text

Text 定义XML 文本节点.

Visitor

Visitor 用于实现Visitor模式.

XPath

XPath 在分析一个字符串后会提供一个XPath 表达式

看名字大致就知道它们的涵义如何了。

要想弄懂这套接口,关键的是要明白接口的继承关系:

一目了然,很多事情都清楚了。大部分都是由<spanlang=en-us style="font-family:&quot;Courier New&quot;">Node继承来的。知道这些关系,将来写程序就不会出现ClassCastException<spanstyle='font-family:宋体'>了。

下面给出一些例子(部分摘自<spanlang=en-us style="font-family:&quot;Courier New&quot;">DOM4J<spanstyle='font-family:宋体'>自带的文档),简单说一下如何使用。

<spanlang=en-us style="font-family:&quot;Courier New&quot;">1.              读取并解析XML文档:

读写<spanlang=en-us style="font-family:&quot;Courier New&quot;">XML文档主要依赖于org.dom4j.io<spanstyle='font-family:宋体'>包,其中提供<spanlang=en-us style="font-family:&quot;Courier New&quot;;color:black"><ahref=".. local%20settings="" temporary%20internet%20files="" myweb="" myclasses="" dom4j-1.4="" doc="" apidocs="" org="" dom4j="" io="" domreader.html"=""><spanstyle='color:black;text-decoration:none'>DOMReader<spanstyle='font-family:宋体;color:black'>和SAXReader两类不同方式,而调用方式是一样的。这就是依靠接口的好处。

 

    // 从文件读取XML,输入文件名,返回XML文档

    public Document read(String fileName) throws MalformedURLException, DocumentException {

       SAXReader reader = new SAXReader();

       Document document = reader.read(new File(fileName));

       return document;

    }

 

其中,<spanlang=en-us style="font-family:&quot;Courier New&quot;">reader<spanstyle='font-family:宋体'>的read<spanstyle='font-family:宋体'>方法是重载的,可以从InputStream, File, Url等多种不同的源来读取。得到的<spanlang=en-us style="font-family:&quot;Courier New&quot;">Document<spanstyle='font-family:宋体'>对象就带表了整个XML<spanstyle='font-family:宋体'>。

根据本人自己的经验,读取的字符编码是按照<spanlang=en-us style="font-family:&quot;Courier New&quot;">XML文件头定义的编码来转换。如果遇到乱码问题,注意要把各处的编码名称保持一致即可。

<spanlang=en-us style="font-family:&quot;Courier New&quot;">2.    取得Root节点

读取后的第二步,就是得到<spanlang=en-us style="font-family:&quot;Courier New&quot;">Root节点。熟悉XML<spanstyle='font-family:宋体'>的人都知道,一切XML<spanstyle='font-family:宋体'>分析都是从Root<spanstyle='font-family:宋体'>元素开始的。

 

   public Element getRootElement(Document doc){

       return doc.getRootElement();

    }

 

<spanlang=en-us style="font-family:&quot;Courier New&quot;">3.    遍历XML

DOM4J提供至少<spanlang=en-us style="font-family:&quot;Courier New&quot;">3种遍历节点的方法:

1) 枚举<spanlang=en-us style="font-family:&quot;Courier New&quot;">(Iterator)

 

    // 枚举所有子节点

    for ( Iterator i = root.elementIterator(); i.hasNext(); ) {

       Element element = (Element) i.next();

       // do something

    }

    // 枚举名称为foo的节点

    for ( Iterator i = root.elementIterator(foo); i.hasNext();) {

       Element foo = (Element) i.next();

       // do something

    }

    // 枚举属性

    for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {

       Attribute attribute = (Attribute) i.next();

       // do something

    }

2)递归<spanlang=en-us style="font-family:&quot;Courier New&quot;">

递归也可以采用<spanlang=en-us style="font-family:&quot;Courier New&quot;">Iterator<spanstyle='font-family:宋体'>作为枚举手段,但文档中提供了另外的做法

 

    public void treeWalk() {

       treeWalk(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....

           }

       }

}

 

3) Visitor模式

最令人兴奋的是<spanlang=en-us style="font-family:&quot;Courier New&quot;">DOM4J<spanstyle='font-family:宋体'>对Visitor<spanstyle='font-family:宋体'>的支持,这样可以大大缩减代码量,并且清楚易懂。了解设计模式的人都知道,<spanlang=en-us style="font-family:&quot;Courier New&quot;">Visitor<spanstyle='font-family:宋体'>是GOF<spanstyle='font-family:宋体'>设计模式之一。其主要原理就是两种类互相保有对方的引用,并且一种作为<spanlang=en-us style="font-family:&quot;Courier New&quot;">Visitor<spanstyle='font-family:宋体'>去访问许多Visitable<spanstyle='font-family:宋体'>。我们来看DOM4J<spanstyle='font-family:宋体'>中的Visitor<spanstyle='font-family:宋体'>模式(<spanstyle='font-family:宋体'>快速文档中没有提供)

只需要自定一个类实现<spanlang=en-us style="font-family:&quot;Courier New&quot;">Visitor<spanstyle='font-family:宋体'>接口即可。

 

        public class MyVisitor extends VisitorSupport {

           public void visit(Element element){

               System.out.println(element.getName());

           }

           public void visit(Attribute attr){

               System.out.println(attr.getName());

           }

        }
 
        调用:  root.accept(new MyVisitor())

    Visitor<spanstyle='font-family:宋体'>接口提供多种Visit()<spanstyle='font-family:宋体'>的重载,根据XML<spanstyle='font-family:宋体'>不同的对象,将采用不同的方式来访问。上面是给出的Element<spanlang=en-us style="font-family:&quot;Courier New&quot;">Attribute<spanstyle='font-family:宋体'>的简单实现,一般比较常用的就是这两个。VisitorSupportDOM4J<spanstyle='font-family:宋体'>提供的默认适配器,Visitor接口的<spanlang=en-us style="font-family:&quot;Courier New&quot;">Default Adapter<spanstyle='font-family:宋体'>模式,这个模式给出了各种visit(*)的空实现,以便简化代码。

    <spanstyle='font-family:宋体'>注意,这个Visitor<spanstyle='font-family:宋体'>是自动遍历所有子节点的。如果是root.accept(MyVisitor),将遍历子节点。我第一次用的时候,认为是需要自己遍历,便在递归中调用<spanlang=en-us style="font-family:&quot;Courier New&quot;">Visitor<spanstyle='font-family:宋体'>,结果可想而知。

4. XPath<spanstyle='font-family:宋体'>支持

    DOM4J<spanstyle='font-family:宋体'>对XPath<spanstyle='font-family:宋体'>有良好的支持,如访问一个节点,可直接用XPath选择。

 

   public void bar(Document document) {

        List list = document.selectNodes( //foo/bar );

        Node node = document.selectSingleNode(//foo/bar/author);

        String name = node.valueOf( @name );

     }

 

<spanlang=en-us style="font-size:10.0pt;font-family:&quot;Courier New&quot;;background:white">    <spanstyle='font-size:10.0pt;font-family:宋体;background:white'>例如,如果你想查找<spanlang=en-us style="font-size:10.0pt;font-family:&quot;Courier New&quot;;background:white">XHTML<spanstyle='font-size:10.0pt;font-family:宋体;background:white'>文档中所有的超链接,下面的代码可以实现:<spanstyle='font-size:10.0pt;font-family:"courier new"'="">

 

    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();

        }

     }

 

<spanlang=en-us style="font-size:10.0pt;font-family:&quot;Courier New&quot;">5. <spanstyle='font-size:10.0pt;font-family:宋体'>字符串与XML<spanstyle='font-size:10.0pt;font-family:宋体'>的转换

<spanstyle='font-size:10.0pt;font-family:宋体'>有时候经常要用到字符串转换为XML<spanstyle='font-size:10.0pt;font-family:宋体'>或反之,

 
    // XML转字符串 

  Document document = ...;

    String text = document.asXML();

// 字符串转XML

    String text = <person> <name>James</name> </person>;

    Document document = DocumentHelper.parseText(text);

 

<spanlang=en-us style="font-size:10.0pt;font-family:&quot;Courier New&quot;">6 <spanstyle='font-size:10.0pt;font-family:宋体'>用XSLT<spanstyle='font-size:10.0pt;font-family:宋体'>转换XML

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章