2012-04-10 32 views
0

我對xsl非常陌生,試圖編寫腳本來解析xml消息並調用模板(我無法控制格式化輸入)。 XML消息中的某些字段可能會出現多次;在這些情況下,我想在「StringValue」的末尾添加一個數字,並將其傳遞到調用模板的with-param =「pet」中,該模板指定它是哪個出現位置。XSL如何將文本與xsl:number連接起來?

下面的代碼似乎做我想要的;但XML Spy說這是無效的XML。有沒有更好的方法來追加「狗/彩色」的每個模板匹配的「StringValue」和「1」,「StringValue」和「2」等?

例如:

<xsl:template match="Dog/Color"> 
    <xsl:call-template name="FormatContents"> 
      <xsl:with-param name="pet">StringValue<xsl:number level="any"/></xsl:with-param> 
      <xsl:with-param name="color"> 
        <xsl:value-of select="."/> 
      </xsl:with-param> 
    </xsl:call-template> 
</xsl:template> 

提前感謝!

+0

http://stackoverflow.com/questions/10090271/xsl-how-to-concatenate -text-with-xslnumber – thejartender 2012-05-25 17:39:21

回答

2

你給的片段是有效的,你確定從該位附帶的錯誤?發佈完整的例子總是最好的。

輸入:

<Dog> 
<Color>Red</Color> 
<Color>Green</Color> 
</Dog> 

XSLT 1:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:template match="Dog/Color"> 
<xsl:call-template name="FormatContents"> 
    <xsl:with-param name="pet">StringValue<xsl:number level="any"/></xsl:with-param> 
    <xsl:with-param name="color"> 
    <xsl:value-of select="."/> 
    </xsl:with-param> 
</xsl:call-template> 
</xsl:template> 

<xsl:template name="FormatContents"> 
<xsl:param name="pet"/> 
<xsl:param name="color"/> 
[<xsl:value-of select="$pet"/>][<xsl:value-of select="$color"/>] 
</xsl:template> 
</xsl:stylesheet> 

輸出:

[StringValue1][Red] 


[StringValue2][Green] 
+0

感謝David的迴應;在返回並進行雙重檢查後,我發現我的錯誤來自XMLSpy未看到呼叫模板。 – Mrc0113 2012-04-10 16:19:03

0

我認爲,你想要的是position() - 即:

<xsl:template match="Dog/Color"> 
    <xsl:call-template name="FormatContents"> 
    <xsl:with-param name="pet">StringValue<xsl:value-of select="position()"/></xsl:with-param> 
    <xsl:with-param name="color"> 
     <xsl:value-of select="."/> 
    </xsl:with-param> 
    </xsl:call-template> 
</xsl:template> 
+0

position()不會(一般地)給出與xsl相同的數字:number level =「any」 – 2012-04-10 15:06:54

相關問題