Transform an integer value to a repeated character

前端 未结 3 1034
攒了一身酷
攒了一身酷 2021-01-18 10:00

When my XSL stylesheets encounters this node:


...it should transform it into this node:



        
相关标签:
3条回答
  • 2021-01-18 10:24

    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!

    0 讨论(0)
  • 2021-01-18 10:40

    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>
    
    0 讨论(0)
  • 2021-01-18 10:45

    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.

    0 讨论(0)
提交回复
热议问题