【问题标题】:Recursive xsl transformation递归 xsl 转换
【发布时间】:2023-03-24 01:36:01
【问题描述】:

我有一个以下格式的 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 的样子:

.------------------------------------------------------------。 |树 |价值 |类型 | |------------------------+------------+--------| | '- 测试 | |家长 | | |- 根 | |家长 | | | '- 组 | |家长 | | | |- 一个 | 0 |整数 | | | '- b | - |字符 | | '- 版本 | |家长 | | |- 版本 | “阿尔法” | utf-8 | | '- 额外 | 16.5 | utf-8 | '----------------------------------------------------------'

【问题讨论】:

  • 如果您不想要 XML 输出,为什么要使用 XSL?
  • 查看更新(我希望输出格式类似于 divs/html)
  • @Oded:XSL 除了输出 XML 还有其他用途。举几个例子,它可以像dacwe想要的那样输出到html,如果使用XSL-FO,它可以生成PDF文件,甚至可以生成另一个XSL文档!如此多的选项和功能.. 它不仅限于生成 xml :)

标签: xml xslt transformation


【解决方案1】:

此 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>

往后两列添加数据很简单,自己试试吧。

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2013-09-27
    相关资源
    最近更新 更多