Dom4j是Java访问XML的利器之一,另一个是JDom。记得当年因为粗掌握点JDomAPI但项目要求使用Dom4j还闹一阵情绪,现在看来真是没必要,只花一些时间成本就进去一个新世界绝对是值得做的一件事。更何况JDom因无人更新而停顿了。

Dom4j有两个包,一个是dom4j-1.6.1.jar,它提供基本的XML API支持,如访问节点,属性等。

还有一个是jaxen-1.1-beta-9.jar,它提供XPath支持。

关于XPath的语法,请见转载:XPath基本语法

言归正传,下面请看例程。

1.访问节点群

XML样本:

<applications>
    <application name='chat'>
        <mtLanguage source='ar_ar' target='en_us' />
        <mtLanguage source='zh_cn' target='en_us' />
        <mtLanguage source='zh_tw' target='en_us' />
        <mtLanguage source='en_us' target='ar_ar' />
        <mtLanguage source='en_us' target='zh_cn' />
        <mtLanguage source='en_us' target='zh_tw' />
        <mtLanguage source='en_us' target='fr_fr' />
        <mtLanguage source='en_us' target='de_de' />
        <mtLanguage source='en_us' target='it_it' />
        <mtLanguage source='en_us' target='ja_jp' />
        <mtLanguage source='en_us' target='ko_kr' />
        <mtLanguage source='en_us' target='pt_br' />
        <mtLanguage source='en_us' target='ru_ru' />
        <mtLanguage source='en_us' target='es_es' />
        <mtLanguage source='fr_fr' target='en_us' />
        <mtLanguage source='de_de' target='en_us' />
        <mtLanguage source='it_it' target='en_us' />
        <mtLanguage source='ja_jp' target='en_us' />
        <mtLanguage source='ko_kr' target='en_us' />
        <mtLanguage source='pt_br' target='en_us' />
        <mtLanguage source='ru_ru' target='en_us' />
        <mtLanguage source='es_es' target='en_us' />
    </application>
    <application name='doc'>
        <mtLanguage source='ar_ar' target='en_us' />
        <mtLanguage source='zh_cn' target='en_us' />
        <mtLanguage source='zh_tw' target='en_us' />
        <mtLanguage source='en_us' target='ar_ar' />
        <mtLanguage source='en_us' target='zh_cn' />
        <mtLanguage source='en_us' target='zh_tw' />
        <mtLanguage source='en_us' target='fr_fr' />
        <mtLanguage source='en_us' target='de_de' />
        <mtLanguage source='en_us' target='hi_in' />
        <mtLanguage source='en_us' target='it_it' />
        <mtLanguage source='en_us' target='ja_jp' />
        <mtLanguage source='en_us' target='ko_kr' />
        <mtLanguage source='en_us' target='pt_br' />
        <mtLanguage source='en_us' target='ru_ru' />
        <mtLanguage source='en_us' target='es_es' />
        <mtLanguage source='en_us' target='ur_pk' />
        <mtLanguage source='fr_fr' target='en_us' />
        <mtLanguage source='de_de' target='en_us' />
        <mtLanguage source='hi_in' target='en_us' />
        <mtLanguage source='it_it' target='en_us' />
        <mtLanguage source='ja_jp' target='en_us' />
        <mtLanguage source='ko_kr' target='en_us' />
        <mtLanguage source='pt_br' target='en_us' />
        <mtLanguage source='ru_ru' target='en_us' />
        <mtLanguage source='es_es' target='en_us' />
        <mtLanguage source='ur_pk' target='en_us' />
    </application>
</applications>

现在,如果我想要访问属性为chat的application节点下的所有mtLanguage子节点,XPath应该这样写:

//applications/application[@name='chat']/mtLanguage

而具体操作的Java语句是:

Document doc= DocumentHelper.parseText(responseXML);// 这个responseXML就是上面的XML样例
List<?> elms=doc.selectNodes("//applications/application[@name='chat']/mtLanguage");
System.out.println("There are "+elms.size()+" language pairs available in text translation");

for(Object obj:elms){
     Element elm=(Element)obj;
     System.out.println("From "+elm.attributeValue("source")+" to "+elm.attributeValue("target"));
}

执行上面语句输出如下:

There are 22 language pairs available in text translation
From ar_ar to en_us
From zh_cn to en_us
From zh_tw to en_us
From en_us to ar_ar
From en_us to zh_cn
From en_us to zh_tw
From en_us to fr_fr
From en_us to de_de
From en_us to it_it
From en_us to ja_jp
From en_us to ko_kr
From en_us to pt_br
From en_us to ru_ru
From en_us to es_es
From fr_fr to en_us
From de_de to en_us
From it_it to en_us
From ja_jp to en_us
From ko_kr to en_us
From pt_br to en_us
From ru_ru to en_us
From es_es to en_us

2.访问特定节点

XML样本:

<rep sts="OK" a="trep" tl="zh-CN">
    <docs>
        <d dt="ndoc" did="d20160223213120480009045125076363146" lang="en-US"
            ctime="2016-02-23T21:31:20" mtime="2016-02-23T21:31:20" orig="1"
            mime="text/x-mt-xml" wc="2">
            <p pid="1" wc="2">
                <s sid="1">
                    <t tid="1" tt="orig" wc="2">Good evening</t>
                </s>
            </p>
        </d>
        <d dt="ndoc" did="d20160223213120480009045125076363146" lang="zh-CN"
            ctime="2016-02-23T21:31:20" mtime="2016-02-23T21:31:20" orig="0"
            mime="text/x-mt-xml" sc="100.00" wc="1">
            <p pid="1" wc="1">
                <s sid="1">
                    <t tid="1" tt="mt" src="mt" sc="100.00" wc="1">晚上好</t>
                </s>
            </p>
        </d>
    </docs>
</rep>

如果我想得到上文中“晚上好”这段文字,XPath应该这样写

//rep/docs/d[last()]/p/s/t

对应的Java代码是:

Document doc= DocumentHelper.parseText(responseXML);
Element elm = (Element) doc.selectSingleNode("//rep/docs/d[last()]/p/s/t");
targetTxt=elm.getText();

3.取属性

XML样本:

<rep sts="OK" a="trep" tl="zh-CN">
    <docs>1</docs>
</rep>

要取根节点rep的sts属性,XPath可以这样写:

//rep/@sts

而对应的Java语句是:

System.out.println("XML="+responseXML);
Document doc= DocumentHelper.parseText(responseXML);
Attribute attr = (Attribute) doc.selectSingleNode("//rep/@sts");      

return attr.getText();

爪哇国新游记之三十四----Dom4j的XPath操作的更多相关文章

  1. 爪哇国新游记之十四----初试JDBC

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import ...

  2. 爪哇国新游记之十九----使用Stack检查数字表达式中括号的匹配性

    /** * 辅助类 * 用于记载字符和位置 * */ class CharPos{ char c; int pos; public CharPos(char c,int pos){ this.c=c; ...

  3. 爪哇国新游记之二十二----排序判断重复时间复杂度为2n的位图法

    import java.util.ArrayList; import java.util.List; /** * 位图法 * 用于整型数组判重复,得到无重复列表 * */ public class B ...

  4. 爪哇国新游记之二十九----访问URL获取输入流

    代码: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import ...

  5. 爪哇国新游记之二十八----从url指定的地址下载文件到本地

    package download; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; ...

  6. Dynamics CRM 2015/2016新特性之三十四:有了插件日志,调试插件so easy!

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复217或者20160330可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  7. 爪哇国新游记之十三----XML文件读写

    /** * XML读写示例 * @author hx * */ public class XmlReaderWriter{ /** * 读取一个XML文件,返回一个雇员链表 * @param file ...

  8. 爪哇国新游记之七----使用ArrayList统计水果出现次数

    之前学习制作了DArray,了解ArrayList就容易了. /** * 用于存储水果名及数量 * */ public class Fruit{ private String name; public ...

  9. 爪哇国新游记之二----用于计算三角形面积的Point类和TAngle类

    这次尝试用两个类完成一个面积计算任务: Point类代表平面上的点: public class Point { private float x; private float y; public Poi ...

随机推荐

  1. Hadoop分布式文件系统:架构和设计要点

    原文:http://hadoop.apache.org/core/docs/current/hdfs_design.html 一.前提和设计目标 1.硬件错误是常态,而非异常情况, HDFS可能是有成 ...

  2. JS让input按钮不能点击

    <input value="开通" type="button" id="tijiao" class="button" ...

  3. 分布式架构高可用架构篇_01_zookeeper集群的安装、配置、高可用测试

    参考: 龙果学院http://www.roncoo.com/share.html?hamc=hLPG8QsaaWVOl2Z76wpJHp3JBbZZF%2Bywm5vEfPp9LbLkAjAnB%2B ...

  4. UVa 11624 Fire!(BFS)

    Fire! Time Limit: 5000MS   Memory Limit: 262144KB   64bit IO Format: %lld & %llu Description Joe ...

  5. IE6 BUG 汇总

    1.IE6双倍边距bug 当页面内有多个连续浮动时,如本页的图标列表是采用左浮动,此时设置li的左侧margin值时,在最左侧呈现双倍情况.如外边距设置为10px, 而左侧则呈现出20px,解决它的方 ...

  6. 【转】我们应该如何去了解JavaScript引擎的工作原理

    原文地址:http://www.nowamagic.net/librarys/veda/detail/1579 昨天收到一封来自深圳的一位前端童鞋的邮件,邮件内容如下(很抱歉,未经过他的允许,公开邮件 ...

  7. java list<int>报错

    请问一下在java中的List<int> list=new List<int>();这条语句的两个int处会报错,请问为什么? 答: 两处错误:第一:List是接口,需要实现类 ...

  8. vi 编辑器常用命令

    VI编辑器可以分为3种状态,它们分别是命令模式.输入模式以及末行模式,VI运行后默认进入命令模式. 命令模式:控制屏幕光标的移动,字符.单词或行的删除.替换,复制粘贴数据以及由此进入插入模式和末行模式 ...

  9. PHP实现远程下载文件到本地

    PHP实现远程下载文件到本地 投稿:hebedich 字体:[增加 减小] 类型:转载   经常写采集器发布接口需要使用到远程附件的功能,所以自己写了一个PHP远程下载文件到本地的函数,一般情况下已经 ...

  10. 【IOS笔记】Windows

    Windows Every iOS application needs at least one window—an instance of the UIWindow class—and some m ...