Wednesday, December 27, 2023

XML data grouping with XSLT 3.0, illustrations

I've just been playing this morning, writing an XSLT 3.0 stylesheet, that does grouping of an XML input data as follows (that I wish to share with XML and XSLT community).

XML input document,

<root>

  <a>

    <m/>

  </a>

  <b>

    <n/>

  </b>

  <a>

    <o/>

  </a>

  <a>

    <p/>

  </a>

  <a>

    <q/>

  </a>

  <b>

    <r/>

  </b>

  <b>

    <s/>

  </b>

</root>


XSLT 3.0 stylesheet, that does grouping of XML document's data mentioned above (i.e, grouping of xml element children of element "root"),

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"                

                         version="3.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/root">

     <xsl:for-each-group select="*" group-by="name()">

        <xsl:element name="{current-grouping-key()}">

           <xsl:copy-of select="current-group()/*"/>

        </xsl:element>

     </xsl:for-each-group>

  </xsl:template>

</xsl:stylesheet>


The XSLT transformation output, of this XML document transform is following,

<?xml version="1.0" encoding="UTF-8"?><a>

  <m/>

  <o/>

  <p/>

  <q/>

</a><b>

  <n/>

  <r/>

  <s/>

</b>


The XML data grouping algorithm implemented by the XSLT stylesheet illustrated above is following,

The XML element children of element "root", are formed into multiple groups (there are two XML data groups that're possible for this stylesheet transformation example.) on the basis of XML element names (the XML sibling elements which are child elements of element "root").

I hope that, this XSLT stylesheet example has been useful for us to study.

This XSLT stylesheet example, has been tested with Apache XalanJ's XSLT 3.0 prototype processor.

No comments: