4
votes

I am trying to sort xml document using XSLT version 1.0.

My XML looks the following:

<?xml version="1.0" encoding="UTF-8"?>
<testMain>
<test name="test1" enabled="false">
<field name="abc" enabled="false" description="test1">
</field>
<field name="dac" enabled="false" description="test2">
</field>
<field name="aaa" enabled="false" description="test4">
</field>
<field name="cat" enabled="false" description="test3">
</field>
</test>
</testMain>

The result should be in the following format, sorted by name:

<?xml version="1.0" encoding="UTF-8"?>
<testMain>
<test name="test1" enabled="false">
<field name="aaa" enabled="false" description="test4">
</field>
<field name="abc" enabled="false" description="test1">
</field>
<field name="cat" enabled="false" description="test3">
</field>
<field name="dac" enabled="false" description="test2">
</field>
</test>
</testMain>

My code in xslt is the following:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<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="test">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="field">
        <xsl:sort select="name" data-type="text"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

I am not sure why the desired output is not generated. Any help much appreciated.

Thank you

1

1 Answers

0
votes

Since name is an attribute you need to access it with @

<xsl:sort select="@name" data-type="text"/>