[英]Deleting xml nodes using xslt
有誰知道如何僅復制xml文件中的前n個節點並使用xslt刪除其余節點? 可以這么說,我只想復制前10個節點並刪除屬於同一父節點的其余節點。
您應該將它們從結果集中刪除,如下所示:
<!-- note you must to encode 'greater than' and 'lower than' characters -->
<xsl:for-each select="parent/nodes[position() <= 10]">
...
</xsl:for-each>
將以下模板添加到標識轉換中:
<xsl:template match="/*/*[position() < 11]"/>
工作原理:身份轉換將其匹配的任何節點遞歸復制到結果文檔中。 但是身份轉換的匹配標准具有最低的優先級; 如果某個節點被具有更高優先級的任何模板匹配,則將使用該模板。 (優先級規則晦澀難懂,但是它們的設計是如此精心,以至於您幾乎不需要了解它們;通常來說,如果一個節點被兩個模板匹配,則XSLT會選擇模式更具體的模板。)
在這種情況下,我們要說的是,如果節點是頂級元素的子元素(頂級元素是根下的第一個元素或/*
,則其子元素就是/*/*
),並且它在該節點列表中的位置為11或更高,因此不應復制。
編輯:
錢幣。 除最重要的內容外,以上所有內容都是正確的。 我寫的內容將復制除前十個元素之外的所有頂級元素的子元素。
這是您需要的模板的完整(正確)版本:
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*/*[position() > 10]"/>
而已。 第一個模板復制第二個模板不匹配的所有內容。 第二個模板匹配前10個元素之后的所有元素,並且不對其進行任何操作,因此不會將其復制到輸出中。
抱歉,代碼未正確粘貼到下面。 應該是這樣的:
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="inner"/>
<xsl:template match="/*/*[position() < 11]">
<xsl:call-template name="identity"/>
</xsl:template>
使用標識轉換,它將源樹復制到輸出樹,並添加模板以排除要消除的元素。 然后,由於您不想刪除所有模板,而只刪除前十個模板之后的模板,請根據其位置為允許的特殊模板添加一個最終模板:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="inner"/>
<xsl:template match="inner[position() < 11]">
<xsl:call-template name="identity"/>
</xsl:template>
</xsl:stylesheet>
與XML一起使用
<?xml version="1.0" encoding="UTF-8"?>
<outer>
<inner foo="1"/>
<inner foo="2"/>
<inner foo="3"/>
<inner foo="4"/>
<inner foo="5"/>
<inner foo="6"/>
<inner foo="7"/>
<inner foo="8"/>
<inner foo="9"/>
<inner foo="10"/>
<inner foo="11"/>
<inner foo="12"/>
<inner foo="13"/>
<inner foo="14"/>
</outer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.