tags:

views:

38

answers:

3

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!

+2  A: 

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!

AakashM
+1 this is the fastest approach if you know the maximum no. of repetitions beforehand.
Tomalak
Which I do, so this will work.
michielvoo
+2  A: 

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) &gt; 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>
Tomalak
+2  A: 

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"&gt;
    <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.

Dimitre Novatchev
+1 for providing the mandatory XSLT 2.0 answer! :-)
Tomalak
I will have to try if the software (InDesign CS3) supports XSLT 2.0, but good answer, thanks!
michielvoo