Mark
Mark

Reputation: 45

Transform XML with elements to new elements with attributes

I have XML like this:

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

This structure, I would like to convert to the following structure so that it will be able to be bound to my Telerik RadTreeview control:

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

Would this transformation be possible with XSLT and if so, what would that XSLT look like?

Upvotes: 0

Views: 48

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117100

Try it this way:

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

Note that there are no attributes in the given XML example and no instructions on how to handle them if they were found.

Upvotes: 1

Related Questions