Search code examples
xmlxsltxslt-2.0

Filter other than top XML element section using XSLT


I have below xml payload. I would only need the topmost job_information section. Other job_information sections to be filtered out. Is there a way that I can achieve this ?

XML Payload:

<?xml version='1.0' encoding='UTF-8'?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <id>858</id>
        <person>
            <person_id_external>484304</person_id_external>
            <employment_information>
                <user_id>484304</user_id>
                <job_information>
                    <end_date>2020-06-30</end_date>
                    <start_date>2020-06-23</start_date>
                </job_information>
                <job_information>
                    <end_date>2020-06-22</end_date>
                    <start_date>2020-05-11</start_date>
                </job_information>
                <job_information>
                    <end_date>2020-05-10</end_date>
                    <start_date>2020-01-01</start_date>
                </job_information>
            </employment_information>
        </person>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

Expected output:

<?xml version='1.0' encoding='UTF-8'?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <id>858</id>
        <person>
            <person_id_external>484304</person_id_external>
            <employment_information>
                <user_id>484304</user_id>
                <job_information>
                    <end_date>2020-06-30</end_date>
                    <start_date>2020-06-23</start_date>
                </job_information>
            </employment_information>
        </person>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

I tried below XSL script but doesn't work:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 
 <xsl:template match="//CompoundEmployee/person/employment_information/job_information[position()=1]"/>
 
   
 </xsl:stylesheet>

Solution

  • Simply filter out positionally all nodes after first. Since you call the identity transform, simply match directly on needed node, job_information.

    Recall empty templates remove nodes and their contents since you do not apply any style rules to the match. And since the greater than symbol is a special symbol, >, in XML, use the entity, &gt;.

    <xsl:template match="job_information[position() &gt; 1]" />
    

    Online Demo