Sort xml with python by tag
<p>I have an xml</p>

<pre><code>&lt;root&gt;
 &lt;node1&gt;
  &lt;B&gt;text&lt;/B&gt;
  &lt;A&gt;another_text&lt;/A&gt;
  &lt;C&gt;one_more_text&lt;/C&gt;
 &lt;/node1&gt;
 &lt;node2&gt;
  &lt;C&gt;one_more_text&lt;/C&gt;
  &lt;B&gt;text&lt;/B&gt;
  &lt;A&gt;another_text&lt;/A&gt;
 &lt;/node2&gt;
&lt;/root&gt;
</code></pre>

<p>I want get output like:</p>

<pre><code>&lt;root&gt;
 &lt;node1&gt;
  &lt;A&gt;another_text&lt;/A&gt;
  &lt;B&gt;text&lt;/B&gt;
  &lt;C&gt;one_more_text&lt;/C&gt;
 &lt;/node1&gt;
 &lt;node2&gt;
  &lt;A&gt;another_text&lt;/A&gt;
  &lt;B&gt;text&lt;/B&gt;
  &lt;C&gt;one_more_text&lt;/C&gt;
 &lt;/node2&gt;
&lt;/root&gt;
</code></pre>

<p>I tried with some code like:</p>

<pre><code>from xml.etree import ElementTree as et

tr = et.parse(path_in)
root = tr.getroot()
for children in root.getchildren():
    for child in children.getchildren():
        # sort it

tr.write(path_out)        
</code></pre>

<p>I cannot use standard function <code>sort</code> and <code>sorted</code> because it sorted wrong way  (not by tag).
Thanks in advance.</p>

<p>From a similar question : </p>

<pre><code>from lxml import etree

data = """&lt;X&gt;
    &lt;X03&gt;3&lt;/X03&gt;
    &lt;X02&gt;2&lt;/X02&gt;
    &lt;A&gt;
        &lt;A02&gt;Y&lt;/A02&gt;
        &lt;A01&gt;X&lt;/A01&gt;
        &lt;A03&gt;Z&lt;/A03&gt;
    &lt;/A&gt;
    &lt;X01&gt;1&lt;/X01&gt;
    &lt;B&gt;
        &lt;B01&gt;Z&lt;/B01&gt;
        &lt;B02&gt;X&lt;/B02&gt;
        &lt;B03&gt;C&lt;/B03&gt;
    &lt;/B&gt;
&lt;/X&gt;"""

doc = etree.XML(data,etree.XMLParser(remove_blank_text=True))

for parent in doc.xpath('//*[./*]'): # Search for parent elements
  parent[:] = sorted(parent,key=lambda x: x.tag)

print etree.tostring(doc,pretty_print=True)
</code></pre>

<p>result : </p>

<pre><code>&lt;X&gt;
  &lt;A&gt;
    &lt;A01&gt;X&lt;/A01&gt;
    &lt;A02&gt;Y&lt;/A02&gt;
    &lt;A03&gt;Z&lt;/A03&gt;
  &lt;/A&gt;
  &lt;B&gt;
    &lt;B01&gt;Z&lt;/B01&gt;
    &lt;B02&gt;X&lt;/B02&gt;
    &lt;B03&gt;C&lt;/B03&gt;
  &lt;/B&gt;
  &lt;X01&gt;1&lt;/X01&gt;
  &lt;X02&gt;2&lt;/X02&gt;
  &lt;X03&gt;3&lt;/X03&gt;
&lt;/X&gt;
</code></pre>

<p>You can find more information here : <a href="http://effbot.org/zone/element-sort.htm" rel="nofollow">http://effbot.org/zone/element-sort.htm</a></p>

python xml sorting