Xpath包含确切的单词

时间:2017-12-06 08:46:32

标签: xml xpath

我有以下XML:

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord of the Rings</title>
    <category>bar</category>
    <author>J. R. R. Tolkien</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>

我想获取数据类别确切包含“foo”的数据:

<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>
<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>

当我尝试:

//*[contains(category, "foo")]

它返回以下元素:

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>

而当我尝试时:

//*[category="foo"]

它返回以下元素:

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>

有没有办法可以获取我的数据。任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

如果类别可能包含以逗号分隔的项目列表:

//category[contains(concat(",", ., ","), ",foo,")]/ancestor::book[1]

需要在之前和之后添加逗号,以避免在找到thefoos

时选择f.e。foo类别