在写之前对etree进行排序

时间:2016-09-09 09:49:58

标签: python sorting elementtree

我正在尝试用python和etree创建一个xml。 现在我想在拧干之前对xml进行排序。这是可能的,如果是的话,怎么样?

objm = json.loads(response.text)

newRoot = ET.Element("root")
tree = ET.ElementTree(newRoot)
i=0
while i < 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)

1 个答案:

答案 0 :(得分:0)

找到解决方案:

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 < 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)