Search code examples
xmlsortingalphabetical

Sorting xml file alphabetically by name tag


I have several large xml files in the following format:

<item>
<name>Name 1</name>
<info>Details 1</info>
</item>

<item>
<name>Name 3</name>
<info>Details 3</info>
</item>

<item>
<name>Name 2</name>
<info>Details 2</info>
</item>

Over time of adding to these it has become ugly. I would like to sort them alphabetically by name tag. I have searched here and found a few different python scripts but they did not work for me. Here is one example of what I've tried:

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")

container = tree.find("item")

data = []
for elem in container:
    key = elem.findtext("name")
    data.append((key, elem))

data.sort()

container[:] = [item[-1] for item in data]

tree.write("test-out.xml")
print "File Written"

Thanks for any help


Solution

  • You really need to have XQuery or XSLT in your toolkit for this kind of job.

    In XQuery:

    <items>{
      for $i in //item order by $i/name return $i
    }</items>
    

    In XSLT (1.0 or later):

    <items xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:for-each select="//item">
        <xsl:sort select="name"/>
        <xsl:copy-of select="."/>
      </xsl:for-each>
    </items>