`
xiaocao000
  • 浏览: 223761 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

Dom4j and XPath

 
阅读更多
很多东西长时间不用, 有些生疏了, 从网上整理了些资料, 丢在这方便以后找.

先上代码:
<?xml version="1.0" encoding="GBK"?>
<resin xmlns="http://caucho.com/ns/resin" xmlns:resin="http://caucho.com/ns/resin/core">  
  <server> 
    <http server-id="" host="*" port="9088"/>  
  </server> 
</resin>



package com.abc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 读写Resin.conf助手类
 */
public class ResinConfHelper {
    private static final String HTTP_SERVER_NODE = "//resin/server/http";
    private static final String DEFAULT_NS = "http://caucho.com/ns/resin";
    private static final String RESIN_NS = "http://caucho.com/ns/resin/core";
    private static final String DEFAULT_NS_KEY = "default";
    private static final String RESIN_NS_KEY = "resin";
    private static final String DEFAULT_ENCODING = "GBK";
    private String resinConfFilePath;
    private Document doc;
    public ResinConfHelper(String resinConfFilePath) {
        this.resinConfFilePath = resinConfFilePath;
    }
    
    public String getHttpPort() {
        return getAttributeValue(HTTP_SERVER_NODE, "port");
    }
    
    public void setHttpPort(String port) {
        setAttributeValue(HTTP_SERVER_NODE, "port", port);
    }
    
    public void setHttpPort(int port) {
        setAttributeValue(HTTP_SERVER_NODE, "port", String.valueOf(port));
    }

    public void init() throws DocumentException {
        Map<String, String> namespaceURIs = new HashMap<String, String>();
        namespaceURIs.put(DEFAULT_NS_KEY, DEFAULT_NS);
        namespaceURIs.put(RESIN_NS_KEY, RESIN_NS);

        DocumentFactory docFactory = new DocumentFactory();
        docFactory.setXPathNamespaceURIs(namespaceURIs);

        SAXReader reader = new SAXReader(docFactory);
        File resinConfFile = new File(resinConfFilePath);
        doc = reader.read(resinConfFile);
    }

    public void save() throws IOException {
        XMLWriter writer = null;
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding(DEFAULT_ENCODING); // 指定XML编码
            writer = new XMLWriter(new FileWriter(resinConfFilePath), format);
            writer.write(doc);
        }
        catch (Exception e) {
            System.err.println(e);
        }
        finally {
            IoUtils.closeQuietly(writer);
        }
    }

    public String getTextValue(String xPath) {
        return getElementByXPath(xPath).getTextTrim();
    }

    public String getAttributeValue(String xPath, String attrName) {
        return getElementByXPath(xPath).attributeValue(attrName);
    }

    private Element setAttributeValue(String xPath, String attrName, String attrValue) {
        return getElementByXPath(xPath).addAttribute(attrName, attrValue);
    }
    
    private Element getElementByXPath(String xPath) {
        return (Element) doc.selectSingleNode(getXPathWithNSByDefualt(xPath));
    }
    
    private static String getXPathWithNSByDefualt(String xpath) {
        xpath = xpath.replaceAll("/(\\w)", "/" + "default:$1"); // replace start with "/"
        xpath = xpath.replaceAll("^(\\w)", "default:$1"); // replace start with word
        return xpath;
    }

    public static void main(String[] args) throws Exception {
        
        String file = "resin.conf";
        ResinConfHelper helper = new ResinConfHelper(file);
        helper.init();
        System.out.println(helper.getHttpPort());
        
        helper.setHttpPort(9088);
        helper.save();
    }

}



---------------------------------------------------------------------
要点:
如果XML带有命名空间, 直接以原来熟悉的XPath语法是得不到相应的节点的.
必须在解析XML之前, 设置相应的命名空间, 并在获取节点前对XPat做相应的处理(加上对应的命名空间标识).

---------------------------------------------------------------------
xpath语法

1、选取节点

XPath 使用路径表达式在 XML 文档中选取节点,节点是沿着路径或者 step 来选取的。
常见的路径表达式:
表达式 描述
nodename选取当前节点的所有子节点
/ 从根节点选取
//从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
.选取当前节点
..选取当前节点的父节点
@选取属性


实例
路径表达式结果
bookstore选取 bookstore 元素的所有子节点
/bookstore选取根元素 bookstore
bookstore/book选取bookstore 下名字为 book的所有子元素。
//book选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book选取bookstore 下名字为 book的所有后代元素,而不管它们位于 bookstore 之下的什么位置。
//@lang选取所有名为 lang 的属性。


2、谓语(Predicates)
谓语用来查找某个特定的节点或者包含某个指定的值的节点。
谓语被嵌在方括号中。
实例
常见的谓语的一些路径表达式:
路径表达式结果
/bookstore/book[1]选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()]选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1]选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3]最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang]选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang='eng']选取所有 title 元素,要求这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00]选取所有 bookstore 元素的 book 元素,要求book元素的子元素 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title选取所有 bookstore 元素中的 book 元素的 title 元素,要求book元素的子元素 price 元素的值须大于 35.00


3、选取未知节点

XPath 通配符可用来选取未知的 XML 元素。
通配符描述
*匹配任何元素节点
@*匹配任何属性节点
node()匹配任何类型的节点

实例
路径表达式结果
/bookstore/*选取 bookstore 元素的所有子节点
//*选取文档中的所有元素
//title[@*]选取所有带有属性的 title 元素。


4、选取若干路径
通过在路径表达式中使用“|”运算符,您可以选取若干个路径。
实例 (将"|"替换为"|")
路径表达式结果
//book/title | //book/price选取所有 book 元素的 title 和 price 元素。
//title | //price选取所有文档中的 title 和 price 元素。
/bookstore/book/title|//price选取所有属于 bookstore 元素的 book 元素的 title 元素,以及文档中所有的 price 元素。


5、XPath 轴
轴可定义某个相对于当前节点的节点集
轴名称结果
ancestor选取当前节点的所有先辈(父、祖父等)
ancestor-or-self选取当前节点的所有先辈(父、祖父等)以及当前节点本身
attribute选取当前节点的所有属性
child选取当前节点的所有子元素。
descendant选取当前节点的所有后代元素(子、孙等)。
descendant-or-self选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following选取文档中当前节点的结束标签之后的所有节点。
namespace选取当前节点的所有命名空间节点
parent选取当前节点的父节点。
preceding选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling选取当前节点之前的所有同级节点。
self选取当前节点。


6、路径

Ø  位置路径表达式
位置路径可以是绝对的,也可以是相对的。
绝对路径起始于正斜杠( / ),而相对路径不会这样。在两种情况中,位置路径均包括一个或多个步,每个步均被斜杠分割:
Ø  绝对位置路径: /step/step/...
Ø  相对位置路径: step/step/...
每个步均根据当前节点集之中的节点来进行计算。
Ø  步(step)包括:
轴(axis):定义所选节点与当前节点之间的树关系
节点测试(node-test):识别某个轴内部的节点
零个或者更多谓语(predicate):更深入地提炼所选的节点集
步的语法:轴名称::节点测试[谓语]
实例

实例
例子结果
child::book选取所有属于当前节点的子元素的 book 节点
attribute::lang选取当前节点的 lang 属性
child::*选取当前节点的所有子元素
attribute::*选取当前节点的所有属性
child::text()选取当前节点的所有文本子节点
child::node()选取当前节点的所有子节点
descendant::book选取当前节点的所有 book 后代
ancestor::book选择当前节点的所有 book 先辈
ancestor-or-self::book选取当前节点的所有book先辈以及当前节点(假如此节点是book节点的话)
child::*/child::price选取当前节点的所有 price 孙。


7、XPath 运算符
运算符描述实例返回值
计算两个节点集//book | //cd返回所有带有 book 和 ck 元素的节点集
+加法6 + 410
-减法6 - 42
*乘法6 * 424
div除法8 div 42
=等于price=9.80如果 price 是 9.80,则返回 true。如果 price 是 9.90,则返回 fasle。
!=不等于price!=9.80如果 price 是 9.90,则返回 true。如果 price 是 9.80,则返回 fasle。
< 小于price<9.80如果 price 是 9.00,则返回 true。如果 price 是 9.90,则返回 fasle。
<=小于或等于price<=9.80如果 price 是 9.00,则返回 true。如果 price 是 9.90,则返回 fasle。
> 大于price>9.80如果 price 是 9.90,则返回 true。如果 price 是 9.80,则返回 fasle。
>=大于或等于price>=9.80如果 price 是 9.90,则返回 true。如果 price 是 9.70,则返回 fasle。
orprice=9.80 or price=9.70如果 price 是 9.80,则返回 true。如果 price 是 9.50,则返回 fasle。
andprice>9.00 and price<9.90如果 price 是 9.80,则返回 true。如果 price 是 8.50,则返回 fasle。
mod计算除法的余数5 mod 21


参考:
http://blog.csdn.net/chifengxin/article/details/7035885
http://www.blogjava.net/eclipser/articles/228367.html
http://blog.csdn.net/blueman2012/article/details/6684177
http://selvemen.iteye.com/blog/1139990
分享到:
评论

相关推荐

    dom4j中XPath用法

    NULL 博文链接:https://wangweiwei358.iteye.com/blog/764548

    dom4j api 参考手册

    为了方便网友编程,将资源...org.dom4j.xpath Provides the core tools needed to use the XPath library org.dom4j.xpp Provides implementation classes to cleanly integrate dom4j with the XML Pull Parser XPP

    Dom4j_使用简介

    Dom4j 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是一个易用...

    Dom4j是一个易用的、开源的库

    Dom4j 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是一个...

    dom4j依赖的jar包

    It is adaptable to many different object models, including DOM, XOM, dom4j, and JDOM. Is it also possible to write adapters that treat non-XML trees such as compiled Java byte code or Java beans as ...

    dom4j的jar包以及说明文档

    dom4j 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 使用指南

    Dom4j 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是一个易用...

    DOM4J使用简介(很实用)

    Dom4j 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是一个易用...

    dom4j帮助文档

    Dom4j 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.

    开源XML解析包dom4j

    DOM4J是dom4j.org出品的一个开源XML解析包,它的网站中这样定义: Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections ...

    Android 创建与解析XML(五)——详解Dom4j方式

    dom4j 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官方网址:...

    Java and XML(英文第三版)

    This third edition of Java and XML covers all major Java XML processing libraries, including full coverage of the SAX, DOM, StAX, JDOM, and dom4j APIs as well as the latest version of the Java API ...

    jaxen-1.1.6.jar

    Jaxen is an XPath engine written in Java to work against a variety of XML based object models such as DOM, dom4j and JDOM together with Java Beans.

    Java and XML, 3rd Edition

    《Java与XML》(第三版)的内容涵盖了所有主要的Java XML处理库程序,全面讲解了SAX、DOM、StAX、JDOM以及dom4j的应用程序编程接口,同时还囊括了最新版本的用于XML处理的Java应用程序编程接口(JAXP)和用于XML绑定...

    jaxen1.1.3

    It is adaptable to many different object models, including DOM, XOM, dom4j, and JDOM. Is it also possible to write adapters that treat non-XML trees such as compiled Java byte code or Java beans as ...

    jQuery详细教程

    四. jQuery实例 jQuery hide() 演示简单的 jQuery hide() 函数。 &lt;script type="text/javascript" src="/jquery/jquery.js"&gt;&lt;/script&gt; $(document).ready(function(){ $("p").click(function(){ $(this)....

    jquery插件使用方法大全

    (4)的方法会在指定的Dom对象上绑定响应ajax执行的事件。 (5)同步加载数据。发送请求时锁住浏览器。需要锁定用户交互操作时使用同步方式。 var html = $.ajax({ url: "some.php", async: false }).responseText;...

    XML轻松学习手册--XML肯定是未来的发展趋势,不论是网页设计师还是网络程序员,都应该及时学习和了解

    4.DOM则为脚本和对象的交流提供一个公共平台,并将结果显示在浏览器窗口。 如果任何一个部分发生错误,都不会得到正确结果。 好了,看到这里,我们已经对XML是如何工作的有一个整体的大致的概念。通过这一章的...

Global site tag (gtag.js) - Google Analytics