Search code examples
xmlxsltxslt-1.0transformationxslt-grouping

XSLT - Missing attributes when grouping the nodes


Here is the minimal but complete samples of XML input, wanted output, code I have and the wrong result I get.

Here is my input XML

<?xml version="1.0"?>
<R>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">1</p>
    </B>
  </M>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">2</p>
    </B>
  </M>
  <M>
    <H>1</H>
     <B>
        <p Ccy="GBP">3</p>
    </B>
  </M>
  <M>
    <H>1</H>
    <B>
        <p Ccy="GBP">4</p>
    </B>
  </M>
</R>

Here is my current XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

    <xsl:output indent="yes" />

     <xsl:template match="/*">
        <R>
            <M>
                <xsl:apply-templates select="M[1]/H | M/B" />
            </M>
        </R>
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

Here is my current output

If you look at the output, Ccy="GBP" is missing in the output. Please look at the expected output.

<?xml version="1.0" encoding="UTF-8"?>
<R xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <M>
      <H>1</H>
      <B>
        <p>1</p>
      </B>
      <B>
        <p>2</p>
      </B>
      <B>
        <p>3</p>
      </B>
      <B>
        <p>4</p>
      </B>
   </M>
</R>

Expected output

<?xml version="1.0" encoding="UTF-8"?>
<R xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <M>
      <H>1</H>
      <B>
        <p Ccy="GBP">1</p>
      </B>
      <B>
        <p Ccy="GBP">2</p>
      </B>
      <B>
        <p Ccy="GBP">3</p>
      </B>
      <B>
        <p Ccy="GBP">4</p>
      </B>
   </M>
</R>

Fiddle: https://xsltfiddle.liberty-development.net/ej9EGbG/31


Solution

  • If you want to copy all attributes simply extend the apply-templates to process them and set up a template that copies them:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    
        <xsl:output indent="yes" />
    
         <xsl:template match="/*">
            <R>
                <M>
                    <xsl:apply-templates select="M[1]/H | M/B" />
                </M>
            </R>
        </xsl:template>
    
        <xsl:template match="*">
            <xsl:element name="{local-name()}">
                <xsl:apply-templates select="@* | node()"/>
            </xsl:element>
        </xsl:template>
    
        <xsl:template match="@*">
            <xsl:copy/>
        </xsl:template>
    
    </xsl:stylesheet>
    

    https://xsltfiddle.liberty-development.net/ej9EGbG/34