Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a character n times in XSLT?

Tags:

xslt

I have a template with a parameter. How can I insert a tab character n times?

n is the value of the parameter.

like image 423
lowerkey Avatar asked Feb 23 '11 09:02

lowerkey


People also ask

How do I count characters in XSLT?

Use string-length(foo) - string-length(translate(foo, ',', '')) .

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.

What is regex in XSLT?

The regex-group() function names which matched string you want to use inside of the xsl:matching-substring element; pass it a 1 to get the first, a 2 to get the second, and so forth. The example above uses it to plug the three matched values inside new city, state, and zip elements created for the output.


2 Answers

In XSLT 2.0:

<xsl:for-each select="1 to $count">&#x9;</xsl:for-each>

(Sadly though, I suspect that if you were using XSLT 2.0 you wouldn't need to ask the question).

Another technique often used with XSLT 1.0 is the hack:

<xsl:for-each select="//*[position() &lt;= $count]">&#x9;</xsl:for-each>

which works provided the number of elements in your source document is greater than the number of tab characters you want to output.

like image 110
Michael Kay Avatar answered Nov 16 '22 02:11

Michael Kay


Just call it recursively; output a tab, then call the same template again with n-1 passed in, if n > 1.

<xsl:template name="repeat">
  <xsl:param name="output" />
  <xsl:param name="count" />
  <xsl:if test="$count &gt; 0">
    <xsl:value-of select="$output" />
    <xsl:call-template name="repeat">
      <xsl:with-param name="output" select="$output" />
      <xsl:with-param name="count" select="$count - 1" />
    </xsl:call-template>
  </xsl:if>
</xsl:template>

As has been pointed out, this example will actually output a minimum of one. In my experience where the output is whitespace, it's usually needed. You can adapt the principle of a recursive template like this any way you see fit.

like image 29
Flynn1179 Avatar answered Nov 16 '22 02:11

Flynn1179