Search code examples
xmlxsltxpathxslt-1.0xslt-2.0

XSLT to transform xml in specific format


Current XML looks like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
    <attribute>
        <name>Attr1</name>
        <value>Attr1 Value 1</value>
    </attribute>
    <attribute>
        <name>Attr2</name>
        <value>Attr 2 Value 1</value>
        <value>Attr 2 Value 2</value>
    </attribute>
</document>

I want new xml to look like following ....

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <document>
        <Attr1>           
            <value>Attr1 Value 1</value>
        </Attr1>
        <Attr2>
            <value>Attr 2 Value 1</value>
            <value>Attr 2 Value 2</value>
        </Attr2>
    </document>

I want to use xslt to make this transformation happen ... my xslt does not work


Solution

  • Here is the solution:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    
      <xsl:template match="/document">
        <document>
          <xsl:apply-templates />
        </document>
      </xsl:template>
    
      <xsl:template match="/document/attribute">
        <xsl:element name="{name}">
          <xsl:copy-of select="value" />
        </xsl:element>
      </xsl:template>
    
    </xsl:stylesheet>
    

    The principal difficulty of this is that you need to create an element with a dynamic name. This is what the <xsl:element name="{name}"> is for. You can put any xpath expression between the braces. Here we wanted the (hopefully unique) name node of the /document/attribute match.