2013-09-22 29 views
0

我試圖將XML文檔轉換爲一些純文本代碼輸出,並希望具有適當的縮進。我沒有找到任何可以實現的信息,我開始嘗試一下。在XSLT中通過with-param傳遞空格模板

目前,我試圖用-參數去獲得根據它應該使用縮進通過空格模板。

<xsl:apply-templates select="foo"> 
    <xsl:with-param name="indent"> </xsl:with-param> 
</xsl:apply-templates> 

只有一個問題......如果參數只包含空格,則不傳遞空格!擁有其他像角色一樣的東西可以傳遞前導空格和尾隨空格,但只要通過空格就會將其更改爲空字符串。

<xsl:apply-templates select="foo"> 
    <xsl:with-param name="indent"> a </xsl:with-param> 
</xsl:apply-templates> 

這是預期的行爲嗎?

我使用xsltproc在Linux上運行的轉換。

讓我知道我可以提供更多的信息。謝謝你的幫助!

回答

1

而不是有你的字符串作爲與<xsl:with-param>元素中的文本節點,將它作爲select屬性。

例如,下面的XSLT樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text"/> 

    <xsl:template match="/"> 

    <!-- With whitespace only. --> 
    <xsl:apply-templates select="foo"> 
     <xsl:with-param name="indent" select=" ' ' "/> 
    </xsl:apply-templates> 

    <!-- Carriage return. -->  
    <xsl:text>&#xd;</xsl:text> 

    <!-- With leading and trailing whitespace. --> 
    <xsl:apply-templates select="foo"> 
     <xsl:with-param name="indent" select=" ' b ' "/> 
    </xsl:apply-templates> 
    </xsl:template> 

    <xsl:template match="foo"> 
    <xsl:param name="indent"/> 

    <xsl:text>$</xsl:text> 
    <xsl:value-of select="$indent"/> 
    <xsl:text>$</xsl:text>  
    </xsl:template> 

</xsl:stylesheet> 

當施加到該輸入XML:

<foo> 
    Bar 
</foo> 

產生以下輸出:

$ $ 
$ b $ 
+0

感謝的很好的例子! – murrekatt

2

我會簡單地使用<xsl:with-param name="indent" select="' '"/>

如果你想通過xsl:with-param內的值,那麼你需要使用

<xsl:with-param name="indent"> 
    <xsl:text> </xsl:text> 
</xsl:with-param> 

<xsl:with-param name="indent" xml:space="preserve"> </xsl:with-param> 
+0

謝謝馬丁!使用xsl:text可以工作,但第二個使用xml:space的建議沒有任何區別。不清楚爲什麼不。 – murrekatt

+0

如何傳遞'$ indent'值以及'select'屬性中的兩個空格? – murrekatt

+0

自己找到了:'concat('',$ indent)'' – murrekatt