Ruup
Ruup

Reputation: 177

python + libxml2: Sorting XML node's elements according to attribute's value

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?

Upvotes: 1

Views: 550

Answers (1)

alecxe
alecxe

Reputation: 473863

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:

Upvotes: 3

Related Questions