I'm trying to sort my XML alphabetically while ensuring that a specific element stays at the top. I have managed to sort it alphabetically, but I cannot get that element to stay. Here is what I have so far:
from lxml import etree
data = """
<Example xmlns="http://www.example.org">
<E>
<A>A</A>
<B>B</B>
<C>C</C>
</E>
<B>B</B>
<D>D</D>
<A>A</A>
<C>C</C>
<F>F</F>
</Example>
"""
doc = etree.XML(data,etree.XMLParser(remove_blank_text=True))
for parent in doc.xpath('//*[./*]'):
parent[:] = sorted(parent,key=lambda x: x.tag)
print etree.tostring(doc,pretty_print=True)
The result from this is:
<Example xmlns="http://www.example.org">
<A>A</A>
<B>B</B>
<C>C</C>
<D>D</D>
<E>
<A>A</A>
<B>B</B>
<C>1</C>
</E>
<F>F</F>
</Example>
Is there anyway I can stop the <E></E> part and its contents from moving?
<E>that makes it an element which should not be sorted? Is it because it has child nodes?