将整数值转换为重复的字符

Mic*_*out 6 xml xslt

当我的XSL样式表遇到此节点时:

<node attribute="3"/>
Run Code Online (Sandbox Code Playgroud)

...它应该将其转换为此节点:

<node attribute="***"/>
Run Code Online (Sandbox Code Playgroud)

我的模板匹配属性并重新创建它,但我不知道如何将值设置为:字符'*'重复的次数与原始属性的值一样多.

<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>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Tom*_*lak 9

通用的递归解决方案(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>
Run Code Online (Sandbox Code Playgroud)

呼叫:

<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>
Run Code Online (Sandbox Code Playgroud)


Aak*_*shM 8

一个相当肮脏但务实的方法是打电话给你期望看到的最高数字attribute,然后使用

substring("****...", 1, $repeat)
Run Code Online (Sandbox Code Playgroud)

*在那个字符串中有多少个s就是你期望的最大数量.但我希望有更好的东西!


Dim*_*hev 7

添加@AakashM和@Tomalak的两个很好的答案,这在XSLT 2.0中自然完成:

这个XSLT 2.0转换:

<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>
Run Code Online (Sandbox Code Playgroud)

当应用于提供的XML文档时:

<node attribute="3"/>
Run Code Online (Sandbox Code Playgroud)

产生想要的结果:

<node attribute="***"/>
Run Code Online (Sandbox Code Playgroud)

请注意如何to<xsl:for-each>指令中使用XPath 2.0 运算符.