Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform an integer value to a repeated character

Tags:

xml

xslt

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!

like image 938
Michiel van Oosterhout Avatar asked Jul 12 '10 11:07

Michiel van Oosterhout


Video Answer


3 Answers

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!

like image 84
AakashM Avatar answered Oct 18 '22 20:10

AakashM


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>
like image 42
Tomalak Avatar answered Oct 18 '22 22:10

Tomalak


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.

like image 7
Dimitre Novatchev Avatar answered Oct 18 '22 20:10

Dimitre Novatchev