I wanted to convert a XML based on attributes to a XML based on child nodes, e.g.:

 

Input

<?xml version="1.0" encoding="utf-8" ?> <people> <person firstname="John" lastname="Smith"/> <person firstname="Michael" lastname="Johnson"/> <person firstname="Jacob" lastname="Williams"/> </people>

Output

<people>
  <person>
    <firstname>John</firstname>
    <lastname>Smith</lastname>
  </person>
  <person>
    <firstname>Michael</firstname>
    <lastname>Johnson</lastname>
  </person>
  <person>
    <firstname>Jacob</firstname>
    <lastname>Williams</lastname>
  </person>
</people>

XSLT

The forum post [http://stackoverflow.com/questions/6496334/c-sharp-to-convert-xml-attributes-to-elements] contains a XSLT script that will just do that.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="http://www.something.com">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:variable name="vNamespace" select="namespace-uri(/*)"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*/*/@*">
    <xsl:element name="{name()}" namespace="{$vNamespace}">
      <xsl:value-of select="."/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="x:Value">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
    <xsl:apply-templates select="@*"/>
  </xsl:template>
</xsl:stylesheet>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.