Question

I would like to sort an XML document's child elements based on the values of a specific attribute.

Here is the test.xml document:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="sort.xsl"?>
<resources>
    <string name="zero">test</string>
    <string name="alfa">test</string>
    <string name="foxtrot">test</string>
    <string name="golf">test</string>
</resources>

Here is sort.xsl:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="resources">
        <assembly>
            <xsl:apply-templates select="string">
                <xsl:sort select="@name" order="ascending" data-type="text" />
            </xsl:apply-templates>
        </assembly>
    </xsl:template>
</xsl:stylesheet>

As far as I know this should match all the string elements under the resources element and try to sort them alphabetically which would give the following output:

<resources>
    <string name="alfa">test</string>
    <string name="foxtrot">test</string>
    <string name="golf">test</string>
    <string name="zero">test</string>
</resources>

It's not working. This is the first XSL transform I've ever written. I'm using XML Notepad 2007 and nothing is showing up in my XSL Output screen. No parsing errors, just a blank screen. Am I doing this completely wrong? I was trying to go off some code found here.

Was it helpful?

Solution

You are processing the string elements in sorted order but you don't have a template matching them so add

<xsl:template match="string">
  <xsl:copy-of select="."/>
</xsl:template>

or a general template to copy nodes if you need to process other nodes as well.

OTHER TIPS

nothing is showing up in my XSL Output screen. No parsing errors, just a blank screen.

If nothing shows up in the output, then the problem is not with sorting. Your stylesheet, when applied to your input, should produce the following result:

<?xml version="1.0"?>
<assembly>testtesttesttest</assembly>

This may not be the result you expect - but it is not blank, so look for the error in how you initiate the transformation, before polishing your stylesheet.

--
BTW, although it's difficult to see, those 4 test strings in the result ARE sorted by the name attribute of the parent string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top