Sort etree before writing
<p>I am trying to make an xml with python and etree.
Now I want to sort the xml before wring it. Is this possible, and if yes, how?</p>

<pre><code>objm = json.loads(response.text)

newRoot = ET.Element("root")
tree = ET.ElementTree(newRoot)
i=0
while i &lt; len(objm):
    newItem = ET.Subelement(newRoot, "item")
    Start_date = datetime.strptime(objm[i]['Start_date'], '%Y-%m-%d %H:%M:%S')
    if (Start_date.date() == datetime.today().date()):
        ET.SubElement(newItem, "Start_date").text = Start_date.strftime("%H:%M")
    ET.SubElement(newItem, "location").text = objm[i]['location']
    i = i+1

##Some sorting on Start_date should be done here##

try:
    tree.write(os.path.join(tempfile.gettempdir(), "filename.xml"))
except Exception,e: 
    print str(e)
</code></pre>

<p>Found the solution:</p>

<pre><code>objm = json.loads(response.text)

objm = sorted(objm, key=lambda k: k.get('Start_date', 0), reverse=False)

newRoot = ET.Element("root")
tree = ET.ElementTree(newRoot)
i=0
while i &lt; len(objm):
    newItem = ET.Subelement(newRoot, "item")
    Start_date = datetime.strptime(objm[i]['Start_date'], '%Y-%m-%d %H:%M:%S')
    if (Start_date.date() == datetime.today().date()):
        ET.SubElement(newItem, "Start_date").text =     Start_date.strftime("%H:%M")
    ET.SubElement(newItem, "location").text = objm[i]['location']
    i = i+1

try:
    tree.write(os.path.join(tempfile.gettempdir(), "filename.xml"))
except Exception,e: 
    print str(e)
</code></pre>

python sorting elementtree