Home > database >  Combine Nodes (XML) with the same ID and their values using XSLT
Combine Nodes (XML) with the same ID and their values using XSLT

Time:11-18

I'm new to XSLT and I'm still learning. I currently face an issue where I need to combine nodes with the same ID. The nodes with the same ID will have different values and these values need to be combined as well.

Below is my initial sample XML:

<OBR>
 <row>
    <ID>T084</ID>
    <col2>Y</col2>
    <col3></col3>
    <col4></col4>
 </row>
 <row>
    <ID>T084</ID>
    <col2></col2>
    <col3>Y</col3>
    <col4></col4>
 </row>
 <row>
    <ID>123456</ID>
    <col2></col2>
    <col3>Y</col3>
    <col4></col4>
 </row>
</OBR>

Given I need to populate empty values with "N" my desired output would be:

<OBR>
 <row>
    <ID>T084</ID>
    <col2>Y</col2>
    <col3>Y</col3>
    <col4>N</col4>
 </row>
 <row>
    <ID>125659</ID>
    <col2>N</col2>
    <col3>Y</col3>
    <col4>N</col4>
 </row>
</OBR>

Can anyone point me in the right direction? Thank you in advance.

CodePudding user response:

It seems you need to do the grouping at two levels:

XSLT 2.0

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

<xsl:template match="/OBR">
    <xsl:copy>
        <xsl:for-each-group select="row" group-by="ID">
            <xsl:copy>
                <xsl:for-each-group select="current-group()/*" group-by="name()">
                    <xsl:element name="{current-grouping-key()}">
                        <xsl:value-of select="(current-group()/text(), 'N')[1]"/>
                    </xsl:element>
                </xsl:for-each-group>
            </xsl:copy>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
  • Related