Commons JXPath - DOM/JDOM Document Access

 

除了 JavaBean,JXPath 也可以访问 DOM/JDOM。

 

示例 XML:

<?xml version="1.0" encoding="utf-8"?>
<book>
    <title>Head First Design Patterns</title>
    <authors>
        <author>
            <firstName>Eric</firstName>
            <lastName>Freeman</lastName>
            <gender>F</gender>
            <birthday>1976-09-14</birthday>            
        </author>
        <author>
            <firstName>ElElisabeth</firstName>
            <lastName>Freeman</lastName>
            <gender>M</gender>
            <birthday>1983-03-27</birthday>
        </author>
    </authors>
    <publisher>
        <name>中国电力出版社</name>
        <address>北京市XX区YY路Z号</address>
        <contacts>
            <contact type='tel'>010-12345678</contact>
            <contact type='fax'>010-87654321</contact>
            <contact type='email'>test@163.com</contact>
        </contacts>
    </publisher>
    <isbn>9787508353937</isbn>
    <price>98</price>
</book>
book.xml

 

DOM/JDOM Document Access

Document document = // get from book.xml ...
JXPathContext context = JXPathContext.newContext(document);
String aBirthday = (String) context.getValue("book/authors/author[firstName='ElElisabeth']/birthday");
String pEmail = (String) context.getValue("book/publisher/contacts/contact[@type='email']");

 

Getting a Value vs. Selecting a Node

JXPathContext 有两组相似的 API:getValue(xpath)/iterate(xpath) 和 selectSingleNode(xpath)/selectNodes(xpath)。对 JavaBeans 和类似的 Java 对象模型,这两组 API 是等效的。但是,对 DOM/JDOM,这两组 API 则有个不同的地方:selectSingleNode(xpath) 和 selectNodes(xpath) 返回的是 Nodes,而 getValue() 和 iterate(xpath) 返回的则是节点的文本内容。
例如,对于相同的 XPath,getValue("/book/isbn") 会返回字符串 "9787508353937",而 selectSingleNode("/book/isbn") 则返回 Element(<isbn>9787508353937</isbn>)(具体类型取决是 DOM 还是 JDOM)。

posted on 2015-08-02 16:02  huey2672  阅读(350)  评论(0编辑  收藏  举报