基于标签名称及其值的知识计算XML文档的XPath

时间:2013-08-27 14:29:50

标签: xml xpath

我有以下XML:

<?xml version="1.0" encoding="UTF-8" ?>
<bookstore>
    <book>
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <account_number>1111 1111 1111 1111</account_number>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book>
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <account_number>2222 2222 2222 2222</account_number>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book>
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <account_number>3333 3333 3333 3333</account_number>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>

我有兴趣找到值 2222 2222 2222 2222 account_number 的XPath。 请指导我如何让XPath了解标签及其价值。

2 个答案:

答案 0 :(得分:3)

//account_number[text()='neededValue']

这意味着所有account_number元素都带有[neededValue]

如果你想要这本书的父元素:

//account_number[text()='neededValue']/ancestor::book/

然后:

//account_number[text()='neededValue']/ancestor::book/OPTION

其中OPTION可以是titleauthoryearprice等,以便通过特定帐户获取该图书中的其他元素号。

答案 1 :(得分:2)

您可以在.谓词中使用上下文节点[a=b],在与右侧部分“2222 2222 2222 2222”进行比较之前,它将转换为字符串

//account_number[.="2222 2222 2222 2222"]

如果您希望父节点基于其子值,则可以将XPath嵌套在另一个谓词中。例如,如果您希望所有具有特定帐号的书籍都可以使用:

//book[account_number[.="2222 2222 2222 2222"]]

------                |-- child value test--|
   ^
   |   |----   matching child condition  -----|
   |
   +--- all book descendants from the root node

要获取这些书籍的标题,请使用title

继续前面的XPath
//book[account_number[.="2222 2222 2222 2222"]]/title

编辑:回到这个答案,有一个更简单的版本

//book[account_number="2222 2222 2222 2222"]/title

在与account_number进行比较之前,"2222 2222 2222 2222"节点已转换为其字符串内容

相关问题