簡體   English   中英

如何使用XSLT在XML文件中復制子元素n次

[英]How to copy child element n times in XML file using XSLT

我對XSLT非常陌生。 我需要將子節點轉換和復制1000次,還需要增加id節點,以使它們每次都不同。

輸入XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<catalog>
    <cd>
        <id>2017</id>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

我的XSLT:但是它只能復制一次

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

我需要的是:請幫忙

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl"   href="test.xsl"?>
<catalog>
    <cd>
        <id>2017</id>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
   </cd>
    <cd>
        <id>2018</id>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
   </cd>
   <cd>
        <id>2019</id>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
   </cd>

    <!-- 997 more times with ID increment +1 each time  -->

</catalog>

在XSLT 1.0中,您可以通過使用遞歸模板來實現。 因此,模板會反復調用自身,每次增加參數直到達到所需的限制。

嘗試使用此XSLT(根據需要將參數5替換為1000)

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="total" select="5" />

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="cd" name="cd">
    <xsl:param name="count" select="1" />
    <xsl:copy>
        <xsl:apply-templates select="@*|node()">
            <xsl:with-param name="count" select="$count" />
        </xsl:apply-templates>
    </xsl:copy>
    <xsl:if test="$count &lt; $total">
        <xsl:apply-templates select=".">
            <xsl:with-param name="count" select="$count + 1" />
        </xsl:apply-templates>
    </xsl:if>
</xsl:template>

<xsl:template match="id">
    <xsl:param name="count" />
    <xsl:copy>
        <xsl:value-of select="number() + $count - 1" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

編輯:如果您想要相同的邏輯,但對於cd下的其他元素,只需修改模板匹配id即可將它們包括在匹配中。 例如..

<xsl:template match="id|year">
    <xsl:param name="count" />
    <xsl:copy>
        <xsl:value-of select="number() + $count - 1" />
    </xsl:copy>
</xsl:template>

可以在http://xsltransform.net/gWEamLv上查看此操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM