Reputation: 160
Let's examine this example:
tree_string = '''
<root>
<must_wrap_anything_inside_this_element> asjkdnasd cass'a s' alsdnjl al <g/>
'asdasjkdhaisbd'assdaewken jka <x id='3'/> kfa;sdf lasd;f naisb fiuabewf <some_random_tag> random stuff </some_random_tag>
yet more text here
</must_wrap_anything_inside_this_element>
</root>
'''
tree = lxml.etree.fromstring(tree_string)
How can I wrap anything (yes anything - text or other elements) inside the must_wrap_anything_inside_this_element
element with another element (like wrapper
, below) resulting in:
result = '''
<root>
<must_wrap_anything_inside_this_element>
<wrapper>
asjkdnasd cass'a s' alsdnjl al <g/>
'asdasjkdhaisbd'assdaewken jka <x id='3'/> kfa;sdf lasd;f naisb fiuabewf <some_random_tag> random stuff </some_random_tag>
yet more text here
</wrapper>
</must_wrap_anything_inside_this_element>
</root>
'''
I am using Python's lxml library. Thanks.
Upvotes: 1
Views: 174
Reputation: 24930
Well, this requires some gymnastics, but is doable....
#locate your target element
target = tree.xpath('//must_wrap_anything_inside_this_element')[0]
#change its tag name....
target.tag="wrapper"
#now create a new element with old, top tag name
tree.insert(0,etree.fromstring('<must_wrap_anything_inside_this_element/>'))
#use the new element as the destination for the old element
destination=tree.xpath('//must_wrap_anything_inside_this_element')[0]
#finally, move the old element to its final resting place...
destination.insert(0,target)
print(etree.tostring(tree).decode())
Output is your desired output.
Upvotes: 1