0

Sort XML with xsd format in ascending order

Because of xsd format in XML my xslt solution was not working. What must be used in case of xsd?

Here is my XML input:

<?XML version="1.0" encoding="utf-8"?>
<test xmlns="tempuri.org/Test.xsd">
    <customer>
        <number>
            4
        </number>
        <number>
            1
        </number>
        <number>
            7
        </number>
    </customer>
</test> 

What I tried:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="w3.org/1999/XSL/Transform">
    <xsl:template match="/*">
        <xsl:copy>
            <xsl:apply-templates>
                <xsl:sort select="number"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet> 

What i expect as output:

<?XML version="1.0" encoding="utf-8"?>
<test xmlns="tempuri.org/Test.xsd">
    <customer>
        <number>
            1
        </number>
        <number>
            4
        </number>
        <number>
            7
        </number>
    </customer>
</test> 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Harshi
  • 11
  • 1
  • You are confusing XSD and namespace.See: https://stackoverflow.com/questions/34758492/xslt-transform-doesnt-work-until-i-remove-root-node/34762628#34762628 – michael.hor257k Jul 27 '20 at 06:21

1 Answers1

-1

Your XML should be (the upper case in the header was causing problems):

<?xml version="1.0" encoding="UTF-8"?>
<test>
    <customer>
        <number>4</number>
        <number>1</number>
        <number>7</number>
    </customer>
</test> 

The xpath of the sort attribute is from the context of the select. ie, You are selecting <number>, so the xpath is form <number>. Hence, the sort is the text of the current node (text()).

this xsl does what you want:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output method="xml" encoding="UTF-8" />
    <xsl:template match="/">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="customer">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()">
                <xsl:sort select="text()"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet> 

if you want to include your xsd

<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="tempuri.org/Test.xsd"">

-then make sure the xsd file exists where you say it is.

Bryn Lewis
  • 580
  • 1
  • 5
  • 14