首页 > 解决方案 > 使用 XPath 1.0 避免路径中的括号

问题描述

以下 XML 结构表示一个包含许多文章的网站。除许多其他内容外,每篇文章都包含其创建日期以及可能任意多个修改日期。我想使用 XPath 1.0获取每篇文章的最后访问日期(创建或最后修改) 。

<website>
    <article>
        <date><strong>22.11.2017</strong></date>
        <edits>
            <edit><strong>17.12.2017</strong></edit>
        </edits>
    </article>
    <article>
        <date><strong>17.4.2016</strong></date>
        <edits></edits>
    </article>
    <article>
        <date><strong>3.5.2011</strong></date>
        <edits>
            <edit><strong>4.5.2011</strong></edit>
            <edit><strong>12.8.2012</strong></edit>
        </edits>
    </article>
    <article>
        <date><strong>12.2.2009</strong></date>
        <edits></edits>
    </article>
    <article>
        <date><strong>23.11.1987</strong></date>
        <edits>
            <edit><strong>3.4.2001</strong></edit>
            <edit><strong>11.5.2006</strong></edit>
            <edit><strong>13.9.2012</strong></edit>
        </edits>
    </article>
</website>

换句话说,预期的输出是:

<strong>17.12.2017</strong>
<strong>17.4.2016</strong>
<strong>12.8.2012</strong>
<strong>12.2.2009</strong>
<strong>13.9.2012</strong>

到目前为止,我只创建了这条路径:

//article/*[self::date or self::edits/edit][last()]

它在每个中寻找date和非空edits节点article并选择后一个。但是我不知道如何访问strong每个此类选择中的最新内容,并且附加到路径末尾的天真//strong[last()]行不通。

我在 XPath 2.0 中找到了一个解决方案。如果我没记错的话,这些路径中的任何一个都应该起作用:

//article/(*[self::date or self::edits/edit][last()]//strong)[last()]
//article/(*//strong)[last()]

但在 XPath 1.0 中,在路径中使用括号是无效的。

标签: xpathxpath-1.0

解决方案


这个 XPath 1.0 表达式

/website/article/descendant::strong[parent::date|parent::edit][last()]

选择节点:

<strong>17.12.2017</strong>

<strong>17.4.2016</strong>

<strong>12.8.2012</strong>

<strong>12.2.2009</strong>

<strong>13.9.2012</strong>

http://www.xpathtester.com/xpath/56d8f7bc4b9c8c064fdad16f22469026中测试

请注意:位置谓词作用于上下文列表。


推荐阅读