XML parser that sorts elements?

jmike at alum.mit.edu jmike at alum.mit.edu
Thu Sep 28 11:33:32 EDT 2006


Paul McGuire wrote:
> >>> doc.childNodes[0].childNodes = sorted(
> ...   [n for n in doc.childNodes[0].childNodes
> ...     if n.nodeType==doc.ELEMENT_NODE],
> ...   key=lambda n:n.nodeName)
> >>> print doc.toprettyxml()
> <?xml version="1.0" ?>
> <booga bar="2" foo="1">
>         <blah>
>                 goodbye
>         </blah>
>         <well>
>                 hello
>         </well>
> </booga>

My requirements changed a bit, so now I'm sorting second level elements
by their values of a specific attribute (where the specific attribute
can be chosen).  But the solution is still mainly what you posted here.
 It was just a matter of supplying a different function for 'key'.
It's up and running live now and all is well.  Thanks again!

(A bonus side effect of this is that it let me sneak "sorted()" into
our test infrastructure, which gave me reason to get our IT guys to
upgrade a mismash of surprisingly old Python versions up to Python 2.5
everywhere.)

--JMike




More information about the Python-list mailing list