Search code examples
xsltxslt-2.0

XSL Move one level Element into other while last one is appearing


Given the input XML data:

<Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
    </Time_Off_Type_Group>
    <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
    <Request_or_Correction>Time Off Request</Request_or_Correction>
</Report_Entry>

As a result, I expect the output data via the condition: "for-each Time_Off_Type_Group move Time_Off_Entry_ID and Request_or_Correction into the Time_Off_Type_Group"

Output example:

<Report_Entry>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Full" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
    <Time_Off_Type_Group>
        <Time_Off_Type Descriptor="Sickness Part" />
        <Time_Off_Entry_ID>2d90199913fa9fae8</Time_Off_Entry_ID>
        <Request_or_Correction>Time Off Request</Request_or_Correction>
    </Time_Off_Type_Group>
</Report_Entry>

Solution

  • Think templates not for-each, so write a template for the Time_Off_Type_Group elements copying the siblings as children and make sure the default idendity copying does not apply to those siblings:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="2.0">
    
      <xsl:output indent="yes"/>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="Time_Off_Type_Group">
          <xsl:copy>
              <xsl:copy-of select="*, ../(* except Time_Off_Type_Group)"/>
          </xsl:copy>
      </xsl:template>
    
      <xsl:template match="Report_Entry/*[not(self::Time_Off_Type_Group)]"/>
    
    </xsl:stylesheet>
    

    https://xsltfiddle.liberty-development.net/bEzkTcn