sandeep himgire
sandeep himgire

Reputation: 53

XSLT - how to group output by common child element value and with hierarchical data in XSLT 2.0

I have an XML file like the below where I may have multiple records with a common child element like so:


    <person>
      <name>Alice</name> /* root node
      <account>001</account>
    </person>
    <person>
      <name>Alice</name>
      <account>002</account>
    </person>

How would I transform this to the below using XSLT 2.0?


    <person>
      <name>Alice</name>
     <child-detail>
      <account>001</account>
      <account>002</account>
     </child-detail>
    </person>

'I'm fairly new to XSLT so please excuse the potentially novice question. Any guidance would be appreciated here. Thanks in advance.'

Upvotes: 1

Views: 348

Answers (1)

Sebastien
Sebastien

Reputation: 2714

You could do it simply using for-each-group.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

  <xsl:output method="xml" indent="yes"/>
  
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="/">
    <xsl:for-each-group select="//person" group-by="name">
      <xsl:copy>
        <xsl:copy-of select="name"/>
        <child-detail>
          <xsl:apply-templates select="current-group()/account"/>
        </child-detail>
      </xsl:copy>
    </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions