首页 > 解决方案 > Xpath 1.0 选择第一个节点回到祖先

问题描述

我的 XML 如下:

<Query>
  <Comp>
    <Pers>
        <Emp>
            <Job>
                <Code>Not selected</Code>
            </Job>
        </Emp>
        <Emp>
            <Job>
                <Code>selected</Code>
            </Job>
        </Emp>
    </Pers>
  </Comp>
</Query>

我有一个 XPath:/Query/Comp/Pers/Emp/Job[Code='selected']/../../../..

结果应该只有一个满足条件的 < Emp >

<Query>
  <Comp>
    <Pers>
        <Emp>
            <Job>
                <Code>selected</Code>
            </Job>
        </Emp>
    </Pers>
  </Comp>
</Query>        

我怎么能得到结果?该系统不适用于祖先::*。我必须使用 '/..' 来填充祖先。

标签: xpath

解决方案


您不必在ancestor此处使用来获取<emp>标签,以下 expath 应该选择<emp>符合您条件的任何标签:

/Query/Comp/Pers/Emp[Job[Code='selected']]

注意:你说你的结果应该是一个,在这种情况下这是正确的,但是这个表达式将返回所有符合你的条件的节点


编辑:

您已经声明您正在使用 XSLT,并且您在下面给了我一些片段,但我仍然不能 100% 确定您的实际结构。您可以使用 XPath 来识别所有不等于 的节点,selected然后使用 XSLT 复制除那些之外的所有内容。

// Copy's all nodes in the input to the output
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()" />
  </xsl:copy>
</xsl:template>

// Matches specifically the Emp records that are not equal to selected and 
// applies no action to them to they do not appear in the output
<xsl:template match="/Query/Comp/Pers/Emp[Job[Code!='selected']]" />

上面的两个模板会将您的输入转换为您想要的输出!


推荐阅读