'I don't understand the output of xsl copy/ sequence
I don't understand the output, I'm getting really confused
<xsl:template match="t[@repeat]">
I'm matching <t repeat="2">
<xsl:variable name="number" select="xsd:integer(@repeat)"/>
storing number 2
<xsl:variable name="result">
<xsl:copy>
<xsl:apply-templates select="*"/>
</xsl:copy>
</xsl:variable>
store all the child elements of , so it's only : <t repeat="3"/>
<xsl:for-each select="1 to $number">
<xsl:sequence select="$result"/>
</xsl:for-each>
shouldn't I just get <t/> <t/> without the attribute repeat="3"?
xsl :
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsl:template match="t">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="t[@repeat]">
<xsl:variable name="number" select="xsd:integer(@repeat)"/>
<xsl:variable name="result">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:variable>
<xsl:for-each select="1 to $number">
<xsl:sequence select="$result"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
xml :
<?xml version="1.0" encoding="utf-8"?>
<t repeat="2">
<t repeat="3"/>
</t>
output:
<t>
<t/>
<t/>
<t/>
</t>
<t>
<t/>
<t/>
<t/>
</t>
Solution 1:[1]
I couldn't understand how your result differs from what you expect. If you want to understand where each part of the result comes from, try changing:
<xsl:variable name="result">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:variable>
to:
<xsl:variable name="result">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:variable>
The result then will be:
<?xml version="1.0" encoding="utf-8"?>
<t repeat="2">
<t repeat="3"/>
<t repeat="3"/>
<t repeat="3"/>
</t>
<t repeat="2">
<t repeat="3"/>
<t repeat="3"/>
<t repeat="3"/>
</t>
which reflects exactly what happens as the result of applying the repeat recursively to both parent and child t.
Do note that your first template is never invoked during this transformation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | michael.hor257k |
