Modifying an XML File
suggest changeImport Element Tree module and open xml file, get an xml element
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root=tree.getroot()
element = root[0] #get first child of root element
An element can be manipulated by changing its fields, adding and modifying attributes, and adding and removing children.
element.set('attribute_name', 'attribute_value') #set the attribute to xml element
element.text="string_text"
If you want to remove an element use Element.remove() method
root.remove(element)
The ElementTree.write() method writes the tree to an XML file.
tree.write('output.xml')
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents