I am trying to use xml.etree.ElementTree to parse a xml file, find a specific tag, append a child to that tag, append another child to the newly created tag and add text to the
You need to specify b
as a parent element for c
.
Also, for getting the a
tag you don't need a loop - just take the root (a
).
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
a = root.find('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(b, 'c')
c.text = 'text3'
print ET.tostring(root)
prints:
text1
text2
text3