manpal
manpal

Reputation: 3

Nesting nodes in xslt

I am trying to create an XSLT to transform an XML document, but I'm having trouble with grouping. I have no problems pulling out information for a single object, but I do not know how to group certain elements using xslt. I have tried xsl:for-each-group and xsl:key for grouping but i was not succesful in transforming.

Input:

<?xml version="1.0" standalone="yes"?>
<root>
    <node1>
        <ID>2</ID>
        <Name>ABCDE</Name>
        <Age>21</Age>
        <Skills>C++ C#</Skills>
        <worklocation>IN</worklocation>
        <designaton>Engineer I</designaton>
    </node1>
    <node2>
        <ID>3</ID>
        <Name>EFGH</Name>
        <Age>12</Age>
        <Skills>java</Skills>
        <worklocation>USA</worklocation>
        <designaton>Engineer II</designaton>
    </node2>
</root>

Desired Output:

<root>
    <node1>
        <ID>2</ID>
        <Name>ABCDE</Name>
        <Age>21</Age>
        <workInfo>
            <Skills>C++ C#</Skills>
            <worklocation>IN</worklocation>
            <designaton>Engineer I</designaton>
        </workInfo>
    </node1>
    <node2>
        <ID>3</ID>
        <Name>EFGH</Name>
        <Age>12</Age>
        <workInfo>
            <Skills>java</Skills>
            <worklocation>USA</worklocation>
            <designaton>Engineer II</designaton>
        </workInfo>
    </node2>
</root>

Upvotes: 0

Views: 130

Answers (1)

zoom
zoom

Reputation: 1756

Use the identity template : see W3C recommandation

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

And then apply a specific template that match the each child node of the root node and will create the workInfo node on the fly.

<xsl:template match="/root/*">
  <xsl:apply-templates select="ID|Name|Age" />
  <workInfo>
    <xsl:apply-templates select="Skills|worklocation|designaton" />
  </workInfo>
</xsl:template>

Upvotes: 2

Related Questions