递归xsl转换

时间:2010-06-04 08:00:21

标签: xml xslt transformation

我有一个关于以下格式的xml文档,并希望使用xsl模板对其进行转换。

我是xsl转换的初学者,我只需要知道如何通过树进行递归,但解决整个问题的方法会很好。

这是xml文档:

<?xml version="1.0" encoding="UTF-8" ?>
<nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <node>
        <type>Parent</type>
        <name>.test</name>
        <node>
            <type>parent</type>
            <name>.test.root</name>
            <node>
                <type>Parent</type>
                <name>.test.root.group</name>
                <node>
                    <type>int</type>
                    <name>.test.root.group.a</name>
                    <value>0</value>
                </node>
                <node>
                    <type>char</type>
                    <name>.test.root.group.b</name>
                    <value>-</value>
                </node>
            </node>
        </node>
        <node>
            <type>parent</type>
            <name>.test.versions</name>
            <node>
                <type>utf-8</type>
                <name>.test.versions.version</name>
                <value>alpha</value>
            </node>
            <node>
                <type>utf-8</type>
                <name>.test.version.extra</name>
                <value>16.5</value>
            </node>
        </node>
    </node>
</nodes>

这就是我希望生成的html看起来像:

    .---------------------------------------------.
    | tree                   | value     | type   |
    |------------------------+-----------+--------|
    | '- test                |           | parent |
    |    |- root             |           | parent |
    |    |  '- group         |           | parent |
    |    |     |- a          | 0         | int    |
    |    |     '- b          | -         | char   |
    |    '- versions         |           | parent |
    |       |- version       | "alpha"   | utf-8  |
    |       '- extra         | 16.5      | utf-8  |
    '---------------------------------------------'

1 个答案:

答案 0 :(得分:3)

这个XSLT将生成一个你想要的树:

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

  <xsl:template match="/">
    <xsl:apply-templates select="nodes/node">
      <xsl:with-param name="indent" select="''" />
      <xsl:with-param name="parent" select="''" />
    </xsl:apply-templates>
  </xsl:template>

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

    <xsl:value-of select="$indent" />
    <xsl:value-of select="substring-after(name/text(), $parent)" />
    <xsl:text>&#xa;</xsl:text>

    <xsl:apply-templates select="./node">
      <xsl:with-param name="indent" select="concat($indent, '    |')" />
      <xsl:with-param name="parent" select="name/text()" />
    </xsl:apply-templates>

  </xsl:template>

</xsl:stylesheet>

向下两列添加数据非常简单,请自行尝试。