Xml XPath选择

Xml XPath选择,xml,xslt,xpath,Xml,Xslt,Xpath,我在编写XPath表达式来选择包含某些元素的节点时遇到了问题,同时排除了我不感兴趣的该元素的同级节点。我怀疑单用XPath无法做到这一点,我需要使用XSLT 使用此源文档 <items> <item id="foo1"> <attr1>val1</attr1> <attr2>val2</attr2> <attr3>val3</attr3>

我在编写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>

瓦尔1
瓦尔2
val3
瓦尔4
瓦尔5
瓦尔6
瓦尔7
瓦尔8
val9
瓦尔10
瓦尔11
我想生成这个结果

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

瓦尔4
瓦尔11

这可以通过XPath实现吗?如果不是,我应该使用什么XSLT转换

这将仅选择具有子项的
s:

/items/item[interestingAttribute]
或者您可以选择
元素本身,如下所示:

/items/item/interestingAttribute

这两个表达式将返回一个节点集,即XML节点列表。如果您真的试图将一个文档转换为另一个文档,您可能会希望使用XSLT,但请记住XPath是XSLT的核心组件,因此您肯定会使用类似于上面的XPath表达式来控制转换。

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>


是否要生成上面的整个xml作为结果?还是只希望xpath中的特定节点在代码库中运行?我更希望生成整个XML文档。但是,如果有排除元素的XPath解决方案,也可以。