2012-02-17 121 views
2

,我有以下類型的XML文檔輸出:XSL:的 「嵌套」 結構

<item> 
    <item> 
    <item> 
    ... (same elements <item> ... </item> here) 
    </item> 
    </item> 
</item> 

...及以下XSL變換:

<xsl:template match="item"><xsl:text> 
open</xsl:text> 
<xsl:apply-templates/><xsl:text> 
close</xsl:text> 
</xsl:template> 

我得到的是:

open 
open 
open 
close 
close 
close 

所以我不知道是否有可能以某種方式得到一個輸出與縮進像此:

open 
    open 
     open 
     close 
    close 
close 

感謝您的幫助!

P.S.通過讓轉換的輸出方法爲HTML,應該可以獲得我想要的。但是,我需要在文本中「直接」縮進,而不是使用任何類型的HTML列表等。

回答

2

該轉化

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

<xsl:template match="item"> 
    <xsl:param name="pIndent" select="' '"/> 

    <xsl:value-of select="concat('&#xA;', $pIndent, 'open')"/> 

    <xsl:apply-templates> 
    <xsl:with-param name="pIndent" 
     select="concat($pIndent, ' ')"/> 
    </xsl:apply-templates> 

    <xsl:value-of select="concat('&#xA;', $pIndent, 'close')"/> 
</xsl:template> 

<xsl:template match="node()[not(self::item)]"> 
    <xsl:apply-templates/> 
</xsl:template> 
</xsl:stylesheet> 

當所提供的XML文檔施加:

<item> 
    <item> 
     <item>  ... 
      <item> ... </item> 
     </item> 
    </item> 
</item> 

產生有用,縮進輸出

open 
    open 
     open 
     open 
     close 
     close 
    close 
    close 

說明

$pIndent參數用於容納空格的字符串被預先考慮到非空白輸出。每當使用xsl:apply-templates時,通過此參數傳遞的值將擴展兩個空格。

0

這很簡單,只需使用裏面的標籤<xsl:text>元素(我不知道如何把它們放在這裏):

<xsl:template match="item"><xsl:text> 
open</xsl:text> 

但是,要實現縮進結構,您需要創建一個命名模板或xpath函數,該函數會輸出多個tab(或多個空格)。

0

有一個'欺騙'的方式來做這個使用子字符串。要修改模板,你已經有了:

<xsl:template match="item"> 
    <xsl:variable name="indent" select="substring('   ',1,count(ancestor::*)*2)" /> 
    <xsl:text>&#10;</xsl:text> 
    <xsl:value-of select="$indent" /> 
    <xsl:text>open</xsl:text> 
    <xsl:apply-templates/> 
    <xsl:text>&#10;</xsl:text> 
    <xsl:value-of select="$indent" /> 
    <xsl:text>close</xsl:text> 
</xsl:template> 

正如你所看到的,它只是插入了一些空間基於有多少祖先的元素已(乘以2),通過利用空格的字符串的一部分。我在這裏使用了10,這意味着它將停止5級縮進,但如果XML比這更深,則可以使用更長的字符串。

它還具有可以通過使用不同字符串很容易進行自定義縮進的優點。例如,您可以使用1-2-3-4-5-6-7-8-9-,如果您想清楚地顯示每行是如何縮進的。

我還用&#10;替換了回車符,只是爲了使代碼更容易縮進可讀性。