user1904898
user1904898

Reputation: 79

Python lxml - Sort by Child

I have a very large XML file, small example below. Is there a short cut to sort by a child? I'm using Python and lxml. I'd like to sort by id when I open the file before I work with the data, does anyone have suggestions of how to do this? I have the data open, and I'm writing the data out in a different format that does not easily provide sorting, so I'd like to sort the data up front if possible. Thanks for any guidance.

XML Example:

<case>
    <id>2</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>3</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>1</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>

I'd like this:

<case>
<id>1</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>2</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>3</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>

Upvotes: 1

Views: 577

Answers (1)

pypat
pypat

Reputation: 1116

You could iterate over all case elements. Then create a list with all the id values. Sort the list. Then you iterate over the list and always output the case element that has that value in id.

It doesn't sound very efficient but it's the first thing that comes to my mind.

Update: I guess it'd be even better to add dicts to a list using the id value as key and sorting the list by those keys. After that you can iterate over the list and write the value of the now sorted dicts to the output.

Upvotes: 1

Related Questions