2010-07-12 67 views
6

当我的XSL样式表遇到此节点:整数值转换为字符重复

<node attribute="3"/> 

...它应该将它转换成节点:

<node 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> 

谢谢!

+0

您正在使用哪种XSLT处理器? – AakashM 2010-07-12 12:00:52

+1

假设我们可以做到这一点...为什么?在数据层上工作不太容易? '***'似乎只对表示层有意义。 – polygenelubricants 2010-07-12 12:01:54

+0

好问题(+1)。查看我对XSLT 2.0解决方案的回答。 – 2010-07-12 16:29:14

回答

8

一个相当肮脏,但务实的做法是使什么是你指望在attribute看到的,然后使用最高的号码的呼叫

substring("****...", 1, $repeat) 

,你在这个字符串当作有许多*小号你期望的最大数量。但我希望有更好的东西!

+0

+1这是最快的方法,如果你知道最大的号码。预先重复。 – Tomalak 2010-07-12 12:09:35

+0

我会这么做,所以这会起作用。 – 2010-07-19 13:32:16

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> 

电话为:

<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> 
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> 

时所提供的XML文档应用:

<node attribute="3"/> 

产生想要的结果

<node attribute="***"/> 

请注意中的XPath 2.0 to运营商是如何使用在<xsl:for-each>指令中。

+0

+1提供强制性的XSLT 2.0答案! :-) – Tomalak 2010-07-12 15:43:28

+0

如果软件(InDesign CS3)支持XSLT 2.0,我将不得不尝试,但很好的答案,谢谢! – 2010-07-19 13:34:50