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>You need to:</p>

<ul>
<li>get the children elements for every top-level "node"</li>
<li>sort them by the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag" rel="nofollow"><code>tag</code> attribute</a> (node's name)</li>
<li>reset the child nodes of each top-level node</li>
</ul>

<p>Sample working code:</p>

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

data = """  &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;"""


root = et.fromstring(data)
for node in root.findall("*"):  # searching top-level nodes only: node1, node2 ...
    node[:] = sorted(node, key=attrgetter("tag"))

print(et.tostring(root))
</code></pre>

<p>Prints:</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>Note that we are not using <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren" rel="nofollow"><code>getchildren()</code> method</a> here (it is actually <em>deprecated</em> since Python 2.7) - using the fact that each <code>Element</code> instance is an iterable over the child nodes.</p>

python xml sorting