2012-02-17 101 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;替换了回车符,只是为了使代码更容易缩进可读性。