You can pass the root
of your tree to the function, then use ElementTree.SubElement
to add a new element to your root
. I've worked with your example:
import xml.etree.ElementTree as ET
def function(root):
new_element = ET.SubElement(root, "abc")
new_element.set("name", "Jonas")
new_element.text = "This is text"
tree = ET.parse("test.xml")
root = tree.getroot()
# Before
print ET.tostring(root)
for element in root.findall("./abc"):
function(root)
# After
print ET.tostring(root)
Before:
<root>
<abc>SomeTree1</abc>
</root>
After:
<root>
<abc>SomeTree1</abc>
<abc name="Jonas">This is text</abc>
</root>
Note that I've polished the xml myself, it's not pretty per default. If you want pretty-print, check out this answer.
Edit: Sorry, I thought from the comments that you wanted to add a new element, not replace the current one. For replacing that element, you could either modify the function above to take in an element, then add a new element before removing the original, or you could just modify the existing element directly:
import xml.etree.ElementTree as ET
def function(element):
element.text = "New text"
element.tag = "New tag"
element.set("name", "Jonas")
tree = ET.parse("test.xml")
root = tree.getroot()
# Before
print ET.tostring(root)
for element in root.findall("./abc"):
function(element)
# After
print ET.tostring(root)
Before:
<root>
<abc>SomeTree1</abc>
</root>
After:
<root>
<New tag name="Jonas">New text</New tag>
</root>