![](/img/trans.png)
[英]Remove all child nodes from the parent except one specific, an xml in c #
[英]Remove all nodes from an xml except for some
我有一個簡單的xml文件,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<garbage1>something</garbage1>
<garbage2>something</garbage2>
<garbage3>something</garbage3>
<item>
<a>
<b/>
<c>123</c>
</a>
<d>456</d>
</item>
<item>
<a>
<b/>
<c>789</c>
</a>
<d>666</d>
</item>
</root>
我想刪除<item>
節點內除<c>
和<d>
之外的所有節點,以得到如下結果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<c>123</c>
<d>456</d>
</item>
<item>
<c>789</c>
<d>666</d>
</item>
</root>
顯然,執行此操作的正確方法是使用標識轉換,然后相應地覆蓋它。 如果我只想刪除<c>
和<d>
,那么就可以了:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- identity transformation-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- override identity transformation-->
<xsl:template match="c|d"/>
</xsl:stylesheet>
好的,所以我只需要否定參數即可消除不是<c>
或<d>
的所有節點。 為什么這不起作用?
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- identity transformation-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- override identity transformation to (apparently not) get rid of all nodes except 'c' and 'd'-->
<xsl:template match="//*[not(local-name() = ('c', 'd'))]"/>
</xsl:stylesheet>
非常感謝大家,我想在這里錯過一些簡單的事情...
首先,實現以下目標的正確方法:
刪除
<item>
節點內除<c>
和<d>
以外的所有節點
是:
XSLT 1.0 / 2.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor::item][not(self::c or self::d)]">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
這匹配c
和d
之外的“ <item>
”之內的任何節點(即item
的后代),並將模板應用於其子節點,而不復制自身。 因此,例如,刪除a
包裝器-但其c
子級仍由身份轉換模板處理。
您的嘗試沒有用,因為您的第二個模板已應用於root
元素。 從那里開始,模板沒有輸出任何內容,也沒有應用任何其他模板-因此處理在該點結束,結果為空。
我找到了一種使用另一種方法解決此問題的方法:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="root">
<root>
<xsl:apply-templates select="@*|node()"/>
</root>
</xsl:template>
<xsl:template match="item">
<item>
<xsl:apply-templates select="@*|node()"/>
</item>
</xsl:template>
<xsl:template match="c | d">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
但是,這仍然使我感到困惑,我的最初想法出了什么問題,因此,如果有人可以幫助我,我將非常高興。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.