Xml – Converting XML elements to XML attributes using XSLT

xmlxslt

We have a current system that outputs an XML file which is in the following format:

<INVENTORY>
   <ITEM>
      <SERIALNUMBER>something</SERIALNUMBER>
      <LOCATION>something</LOCATION>
      <BARCODE>something</BARCODE>
   </ITEM>
</INVENTORY>

I need to use this data to load into the standard .NET 2.0 grid. But the grid needs the XML to be in the following format:

<INVENTORY>
   <ITEM serialNumber="something" location="something" barcode="something">
   </ITEM>
</INVENTORY>

i.e. the child nodes of item need to be converted into attributes of the item node.

Does someone know how this can be done using XSLT?

Best Solution

That should work:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="INVENTORY">
    <INVENTORY>
      <xsl:apply-templates/>
    </INVENTORY>
  </xsl:template>

  <xsl:template match="ITEM">
    <ITEM>
      <xsl:for-each select="*">
        <xsl:attribute name="{name()}">
          <xsl:value-of select="text()"/>
        </xsl:attribute>

      </xsl:for-each>
    </ITEM>
  </xsl:template>
</xsl:stylesheet>

HTH