Home > other >  Grouping of data using XSLT
Grouping of data using XSLT

Time:09-02

I have a xml input as below. I need to club the record-type 6 and the following record-type 4 using xslt (3.0). The first character is the record type. Each record-type 6 can have multiple record-type 4.

<root>
    <row>
        <line>60010010000015</line>
    </row>
    <row>
        <line>40010016009108</line>
    </row>
    <row>
        <line>60010020001556</line>
    </row>
    <row>
        <line>40010026009404</line>
    </row>
    <row>
        <line>40010036009405</line>
    </row>
    <row>
        <line>40010036009406</line>
    </row>
<root>

Expected output:

<root>
   <row>
      <MainRecord>60010010000015</MainRecord>
      <Record4>
        <SubRecord>40010016009108</SubRecord>
      </Record4>
   </row>
   <row>
      <MainRecord>60010020001556</MainRecord>
      <Record4>
        <SubRecord>40010026009404</SubRecord>
        <SubRecord>40010036009405</SubRecord>
        <SubRecord>40010036009406</SubRecord>
      </Record4>
   </row>
</root>

CodePudding user response:

It can be simply:

<xsl:stylesheet version="3.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <xsl:copy>
        <xsl:for-each-group select="row" group-starting-with="row[starts-with(line, '6')]">
            <row>
                <MainRecord>
                    <xsl:value-of select="line" />
                </MainRecord>
                <Record4>
                    <xsl:for-each select="subsequence(current-group(), 2)">
                        <SubRecord>
                            <xsl:value-of select="line" />
                        </SubRecord>
                    </xsl:for-each>
                </Record4>
            </row>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
  • Related