2010-07-12 63 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