Meriam Chelbi
Meriam Chelbi

Reputation: 1

Adding a subElement into a subElement in xml with python

I am working with xml files in python, and I want to ask if there is a way to add a subelement into an other subelement into the xml file. If for the example, the structure of the xml file is as follow, and I want to add a new subelement under the container 'b'. how can I do it ?

<?xml version .....>
<module name=....>
<augment ....>
 <container name="a">
 </container>
 <container name="b">
 </container>
</augment>
</module>

Upvotes: 0

Views: 45

Answers (1)

Maciej Wrobel
Maciej Wrobel

Reputation: 660

If you want to do it in more future-proof way, you may want to use some kind of xml parser, i.e. lxml.etree. You could parse your xml, work on its elements and eventually dump it later back to a file. There is simple working example:

from lxml import etree
xml = '''<module name="x">
<augment name="y">
 <container name="a">
 </container>
 <container name="b">
 </container>
</augment>
</module>'''.strip()

xtree = etree.fromstring(xml) 

for element in xtree.xpath('.//container[@name="b"]'):
    new = etree.Element('something') # create new element to be inserted
    new.set('name', 'xyz') # define some attributes for new element
    element.append(new) # append it to your currently-processed element

print(etree.tostring(xtree,pretty_print=True).decode('ascii'))

For more see lxml documentation (https://lxml.de/tutorial.html)

Upvotes: 2

Related Questions