Reputation: 690
I'm looking for a recipe for python's lxml.etree that will reverse the nesting of elements, turning:
<text>
<name>
<ref>foobar</ref>
</name>
</text>
into:
<text>
<ref>
<name>foobar</name>
</ref>
</text>
I've a feeling this is obvious, but I'm not seeing it.
Upvotes: 1
Views: 533
Reputation: 50517
Something like this?
import lxml.etree as et
from lxml.builder import E
xml = """
<text>
<name>
<ref>foobar</ref>
</name>
</text>
"""
tree = et.fromstring(xml)
for name in tree.findall('name'):
text = name.find('ref').text
tree.replace(name, E.ref(E.name(text)))
print et.tostring(tree)
Upvotes: 2