[英]XPath selection
我在編寫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轉換?
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>
這將僅選擇具有<interestingAttribute>
子<item>
的<item>
:
/items/item[interestingAttribute]
或者,您可以自己選擇<interestingAttribute>
元素,如下所示:
/items/item/interestingAttribute
這兩個表達式將為您提供節點集,即XML節點列表。 如果您確實想將一個文檔轉換為另一個文檔,則可能要使用XSLT,但是請記住XPath是XSLT的核心組件,因此您肯定會使用上述XPath表達式來控制轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.