1

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.

zx485
  • 28,498
  • 28
  • 50
  • 59
egx
  • 389
  • 2
  • 14
  • Look at any introduction and examples to grouping, like https://stackoverflow.com/tags/xslt-grouping/info here on this site, then give it a try with some code. If you run into problems, post the details (minimal but complete XML and XSLT, output you want, error or wrong output you get), together with information about the used XSLT processor. – Martin Honnen Nov 18 '21 at 09:03

1 Answers1

3

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>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51