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>
CodePudding user response:
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)
CodePudding user response:
xml = """<?xml version .....>
<module name=....>
<augment ....>
<container name="a">
</container>
<container name="b">
</container>
</augment>
</module>"""
xml_splits = xml.split('\n')
for i, line in enumerate(xml_splits):
if 'name="b"' in line:
leading_white_space = line[0:line.find(line.strip())]
xml_splits.insert(i 1, leading_white_space ' <container name="c">')
xml_splits.insert(i 2, leading_white_space ' </container>')
break
res = '\n'.join(xml_splits)
print(res)
It's not very elegant but it should cover your case. I simply find the line with your element you want to insert into and then insert the new element with the leading white space from its parent.
