1

I have the following node in an XML-document:

<state>
    <soso value="3"/>
    <good value="1"/>
    <bad value="2"/>
    <unknown value="0"/>
</state>

I need to sort its elements according to the value attribute's value, so that the result is the following:

<state>
    <unknown value="0"/>
    <good value="1"/>
    <bad value="2"/>
    <soso value="3"/>
</state>

How would one do it in python using libxml2?

2
  • Have you solved the issue? Did the answer help? Commented Sep 29, 2014 at 14:48
  • Yes, I did. I can't tell you how though; it's been too long ago. The requirement was to use libxml2 since lxml was not available on the system. I'm sorry for not responding earlier. Commented Jan 8, 2015 at 9:51

1 Answer 1

3

You can sort the children of a state tag using lxml this way:

from lxml import etree

data = """
<state>
    <soso value="3"/>
    <good value="1"/>
    <bad value="2"/>
    <unknown value="0"/>
</state>
"""

state = etree.fromstring(data)
state[:] = sorted(state, key=lambda x: int(x.attrib.get('value')))
print etree.tostring(state)

Prints:

<state>
    <unknown value="0"/>
    <good value="1"/>
    <bad value="2"/>
    <soso value="3"/>
</state>

Note that it really sounds like applying an XSLT transformation is more logical and simple here, see:

See also:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.