[Tutor] ElementTree, iterable container, depth of elements

Dave Angel davea at davea.name
Sat Mar 29 18:01:18 CET 2014


 street.sweeper at mailworks.org Wrote in message:
> I'm trying to sort the order of elements in an xml file, mostly
> to make visual inspection/comparison easier.  The example xml and
> code on http://effbot.org/zone/element-sort.htm get me almost
> what I need, but the xml I'm working with has the element I'm
> trying to sort on one level deeper.
> 
> 
> That page's example xml:
> 
> <phonebook>
>   <entries>
>     <entry>
>       <name>Ned</name>
>       <number>555-8904</number>
>     </entry>
>     <entry>
>       <name>John</name>
>       <number>555-5782</number>
>     </entry>
>     <entry>
>       <name>Julius</name>
>       <number>555-3642</number>
>     </entry>
>   </entries>
> </phonebook>
> 
> 
> And that page's last example of code:
> 
>   import xml.etree.ElementTree as ET
>   tree = ET.parse("data.xml")
>   def getkey(elem):
>     return elem.findtext("number")
>   container = tree.find("entries")
>   container[:] = sorted(container,key=getkey)

That would be more clearly written
      sort(container,key=getkey)

>   tree.write("new-data.xml")
> 
> 
......
> Traceback (most recent call last):
>   File "./xmlSort.py", line 16, in <module>
>     container[:] = sorted(container, key=getkey)
> TypeError: 'NoneType' object is not iterable
> 

That simply tells you that tree.find () returns None. 

> 
> "container[:] = sorted(container, key=getkey)" confuses me,
> particularly because I don't see how the elem parameter is passed
> to the getkey function.
> 

You should play with a list,  sorting it with a key function.  For
 example make a list of strings,  using a key=

def mykey (elem):
      return elem.lower ()

To see what's going on,  add a print to that function,  showing
 yourself that the sort function will call mykey () on each
 element.


I can't help with the xml stuff,  but it seems clear you have to
 produce a find call that gives you the right list.


-- 
DaveA



More information about the Tutor mailing list