sravan kumar
sravan kumar

Reputation: 613

Sort XML sections using XSLT

I would like to sort the dependent_information sections in below xml based on date_of_birth field. Tried below script but it skips other sections like personal_information/employment_information etc

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//CompoundEmployee/person">
        <xsl:copy>
            <xsl:apply-templates select="dependent_information">
                <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Below is the structure of my xml

<?xml version='1.0' encoding='UTF-8'?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <id>22201</id>
        <person>
            <person_id_external>560706</person_id_external>
            <personal_information>
                <first_name>James</first_name>
                <last_name>Tester</last_name>
            </personal_information>
            <employment_information>
                <employment_id>21960</employment_id>
                <start_date>2020-05-01</start_date>
            </employment_information>
            <dependent_information>
                <date_of_birth>2009-05-04</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2004-01-31</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2019-06-02</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
        </person>
        <execution_timestamp>2020-05-28T09:44:10.000Z</execution_timestamp>
        <version_id>1911P0</version_id>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

Upvotes: 0

Views: 34

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use

<xsl:template match="CompoundEmployee/person">
    <xsl:copy>
        <xsl:apply-templates select="*[not(self::dependent_information)]"/>
        <xsl:apply-templates select="dependent_information">
            <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

Upvotes: 1

Related Questions