1

I want to sort an XML file.

Let's assume, we have following XML:

<test>
     <a attribute="sortme2">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
     <a attribute="sortme">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
     <a attribute="sortme1">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
</test>

I want to have following output:

<test>
     <a attribute="sortme">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
     <a attribute="sortme1">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
     <a attribute="sortme2">
        <b>
           <c donttouchme="aaa"/>
        </b>
     </a>
</test>

Can you help me? I would be so glad! Thank you.

Huber
  • 13
  • 2
  • What is the meaning of "donttouchme"? Does that mean you don't want those nodes sorted? And where exactly are you stuck with this? Seems rather trivial. – michael.hor257k Jul 20 '20 at 12:08

1 Answers1

0

Apply the following XSLT:

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

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
    xmlns:qi="http://webqi.org/XMLSchema" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">

<!-- match the root node-->
    <xsl:template match="/">
        <xsl:apply-templates select="*" />
    </xsl:template>

    <xsl:template match="@*|node()">
<!-- copy all elements and attributes-->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()">
<!-- sort on the attribute attribute-->
                <xsl:sort select="@attribute" />
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

To connect the xml to the xsl, save the above as 'yourxsl.xsl', then add this to the top of the xml:

<?xml-stylesheet type="text/xsl" href="yourxsl.xsl"?>

-As described here:

How to link up XML file with XSLT file?

Bryn Lewis
  • 580
  • 1
  • 5
  • 14