Search code examples
xmlxsltxslt-1.0xslt-2.0xslt-grouping

XSLT for picking and grouping elements from XML schema


I have an XML schema where I need to filter specific elements from each node and group those filtered elements into desired XML format.

XML schema is as follows-

<Roots>
 <Root>
  <Result>
   <Row index="1">
    <id>001</id>
    <value>Test Value</value>
   </Row>
   <Row index="2">
    <id>001</id>
    <value>Test Value1</value>
   </Row>
   <Row index="3">
    <id>001</id>
    <value>Test Value2</value>
   </Row>
   <Row index="4">
    <id>002</id>
    <value>Test Value3</value>
   </Row>
   <Row index="5">
    <id>002</id>
    <value>Test Value4</value>
   </Row>
   <Row index="6">
    <id>003</id>
    <value>Test Value5</value>
   </Row>
   <Row index="7">
    <id>003</id>
    <value>Test Value6</value>
   </Row>
   <Row index="8">
    <id>003</id>
    <value>Test Value7</value>
   </Row>
  </Result>
 </Root>
</Root>

I want to select element <id> and <value> from each node <Row> grouping by <id>. The expected XML schema is as follows-

<html>
<body>
<table border="1">
  <tr>
   <td>001</td>
   <td>Test Value</td>
   <td>Test Value1</td>
   <td>Test Value2</td>
  </tr>
  <tr>
   <td>002</td>
   <td>Test Value3</td>
   <td>Test Value4</td>
  </tr>
  <tr>
   <td>003</td>
   <td>Test Value5</td>
   <td>Test Value6</td>
   <td>Test Value7</td>
  </tr>
</table>
</body>
</html>

Could you please help me for the above format. Working XSLT is as follows-

'<xsl:stylesheet version="1.0"     
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Roots/Root/Result">
<html>
 <body>
  <table border="1">
   <xsl:for-each-group select="Row" group-by="id">
    <tr>
     <td><xsl:value-of select="id"/></td>
     <xsl:for-each select="current-group()">
        <td><xsl:value-of select="value"/></td>
    </xsl:for-each>
    </tr>
   </xsl:for-each-group>    
  </table>
 </body>
</html>
</xsl:template>
</xsl:stylesheet>'

Solution

  • this is a standart grouping schema in XSLT 2.0 (i assume that you are using the 2.0 since you didnt specify).

    https://www.xml.com/pub/a/2003/11/05/tr.html

    Check this link and it will help you a lot to shape your algorithm to do what you want.

    If you can share the XSLT code then we could be able to help you more.

    Good Luck