使用元素将XML转换为具有属性的新元素

时间:2014-10-01 08:33:34

标签: xml xslt

我有这样的XML:

<?xml version="1.0"?>
<message>
  <header>
    <number>abc</number>
    <headerType>
      <code>abc</code>
    </headerType>
  </header>
</message>

这个结构,我想转换为以下结构,以便它能够绑定到我的Telerik RadTreeview控件:

<Tree>
    <Node Text="message" Value="message">
        <Node Text="header" Value="header">
            <Node Text="number" Value="number">
                <Node Text="abc" Value="abc" />
    </Node>
            <Node Text="headerType" Value="headerType">
                <Node Text="code" Value="code">
                    <Node Text="abc" Value="abc" />
                </Node>
            </Node>
       </Node>
    </Node>
</Tree>

使用XSLT可以实现这种转换吗?如果是这样,XSLT会是什么样的?

1 个答案:

答案 0 :(得分:1)

以这种方式尝试:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <Tree>
        <xsl:apply-templates select="node()"/>
    </Tree>
</xsl:template>

<xsl:template match="*">
    <Node Text="{local-name()}" Value="{local-name()}">
        <xsl:apply-templates select="node()"/>
    </Node>
</xsl:template>

<xsl:template match="text()">
    <Node Text="{.}" Value="{.}"/>
</xsl:template>

</xsl:stylesheet>

请注意,给定的XML示例中没有属性,如果找到它们,则没有关于如何处理它们的说明。