首页 文章

XPath选择

提问于
浏览
2

我在编写XPath表达式以选择包含某些元素的节点时遇到了麻烦,同时排除了我不感兴趣的这个元素的兄弟节点 . 我怀疑单独使用XPath无法做到这一点而且我需要使用XSLT .

使用此源文档

<items>
    <item id="foo1">
        <attr1>val1</attr1>
        <attr2>val2</attr2>
        <attr3>val3</attr3>
        <interestingAttribute>val4</interestingAttribute>
    </item>
    <item id="foo2">
        <attr1>val5</attr1>
        <attr2>val6</attr2>
        <attr3>val7</attr3>
    </item>
    <item id="foo3">
        <attr1>val8</attr1>
        <attr2>val9</attr2>
        <attr3>val10</attr3>
        <interestingAttribute>val11</interestingAttribute>
    </item>
</items>

我想生成这个结果

<items>
    <item id="foo1">
        <interestingAttribute>val4</interestingAttribute>
    </item>
    <item id="foo3">
        <interestingAttribute>val11</interestingAttribute>
    </item>
</items>

这可以用XPath完成吗?如果没有,我应该使用什么XSLT转换?

2 回答

  • 2

    这将仅选择具有 <interestingAttribute> 子项的 <item>

    /items/item[interestingAttribute]
    

    或者您可以像这样选择 <interestingAttribute> 元素:

    /items/item/interestingAttribute
    

    这两个表达式将返回一个节点集,一个XML节点列表 . 如果您真的想要将一个文档转换为另一个文档,那么您可能希望使用XSLT,但请记住,XPath是XSLT的核心组件,因此您肯定会使用上述XPath表达式来控制转换 .

  • 4

    XPath用于选择特定节点,它不会为您提供所需的树结构 . 最多,您可以从中获取节点列表,并且可以从节点列表中派生树结构 . 如果你真正想要的是选择有趣的属性,你可以尝试这个XPath:

    /items/item/interestingAttribute
    

    如果要生成树,则需要XSLT . 这个模板应该这样做:

    <xsl:template match="/items">
        <xsl:copy>
            <xsl:for-each select="item[interestingAttribute]">
                <xsl:copy>
                    <xsl:copy-of select="@* | interestingAttribute"/>
                </xsl:copy>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
    

相关问题