XSLT: Transform Node to Attribute

The following is code snippet demonstrates an XSLT transformation of a node to an attribute.

This is the sample XML File,

<Head>
   <Child>
      <Grandchild1>Test1</Grandchild1>
      <Grandchild2>Test2</Grandchild2>
      <Grandchild3>Test3</Grandchild3>
   </Child>
</Head>

The final output expected is,

<Head>
   <Child Grandchild1="Test1" Grandchild2="Test2" Grandchild3="Test3">
   </Child>
</Head>

Note: The grandchild nodes are converted into attributes.

Here is the XSLT for the same,

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

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

Have fun.

Tags: , , , ,

Leave a Reply