kepioo wrote:
> Hi all,
> 
> I am trying to write an xml aggregator, but so far, i've been failing
> miserably.
> 
> what i want to do :
> 
> i have entries, in a list format :[[key1,value],[key2,value],[
> key3,value]], value]
> 
> example :
> [["route","23"],["equip","jr2"],["time","3pm"]],"my first value"]
>  [["route","23"],["equip","jr1"],["time","3pm"]],"my second value"]
>  [["route","23"],["equip","jr2"],["time","3pm"]],"my third value"]
>  [["route","24"],["equip","jr2"],["time","3pm"]],"my fourth value"]
>  [["route","25"],["equip","jr2"],["time","3pm"]],'"my fifth value"]
> 
>   the tree i want in the end would be :

assuming that the actual order of the subelements doesn't matter, you 
could simply sort the array, and use groupby to group related tags:

import elementtree.ElementTree as ET
import itertools, operator

data = [
     ([["route","23"],["equip","jr2"],["time","3pm"]],"my first value"),
     ([["route","23"],["equip","jr1"],["time","3pm"]],"my second value"),
     ([["route","23"],["equip","jr2"],["time","3pm"]],"my third value"),
     ([["route","24"],["equip","jr2"],["time","3pm"]],"my fourth value"),
     ([["route","25"],["equip","jr2"],["time","3pm"]],"my fifth value")
     ]


def group(data, index):
     return itertools.groupby(sorted(data), lambda x: x[0][index])

root = ET.Element("result")

for key, items in group(data, 0):
     route = ET.SubElement(root, key[0], id=key[1])
     for key, items in group(items, 1):
        equip = ET.SubElement(route, key[0], id=key[1])
        for key, items in group(items, 2):
            time = ET.SubElement(equip, key[0], id=key[1])
            for data in items:
                ET.SubElement(time, "data").text = data[1]

ET.dump(root)

if you want prettyprinted output, use this function

     http://effbot.org/zone/element-lib.htm#prettyprint

on the resulting tree.

</F>

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to