When my XSL stylesheets encounters this node:
<node attribute="3"/>
...it should transform it into this node:
<node attribute="***"/>
My template matches the attribute and recreates it, but I don't know how to set the value to: the character '*' repeated as many times as the value of the original attribute.
<xsl:template match="node/@attribute">
<xsl:variable name="repeat" select="."/>
<xsl:attribute name="attribute">
<!-- What goes here? I think I can do something with $repeat... -->
</xsl:attribute>
</xsl:template>
Thanks!
A fairly dirty but pragmatic approach would be to make a call on what's the highest number you ever expect to see in attribute
, then use
substring("****...", 1, $repeat)
where you have as many *
s in that string as that maximum number you expect. But I hope that there's something better!
Generic, recursive solution (XSLT 1.0):
<xsl:template name="RepeatString">
<xsl:param name="string" select="''" />
<xsl:param name="times" select="1" />
<xsl:if test="number($times) > 0">
<xsl:value-of select="$string" />
<xsl:call-template name="RepeatString">
<xsl:with-param name="string" select="$string" />
<xsl:with-param name="times" select="$times - 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
Call as:
<xsl:attribute name="attribute">
<xsl:call-template name="RepeatString">
<xsl:with-param name="string" select="'*'" />
<xsl:with-param name="times" select="." />
</xsl:call-template>
</xsl:attribute>
Adding to the two nice answers of @AakashM and @Tomalak, this is done naturally in XSLT 2.0:
This XSLT 2.0 transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@attribute">
<xsl:attribute name="{name()}">
<xsl:for-each select="1 to .">
<xsl:value-of select="'*'"/>
</xsl:for-each>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<node attribute="3"/>
produces the wanted result:
<node attribute="***"/>
Do note how the XPath 2.0 to
operator is used in the <xsl:for-each>
instruction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With