Python Language Modifying an XML File


Example

Import 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

Element object can be manipulated by changing its fields, adding and modifying attributes, 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)

ElementTree.write() method used to output xml object to xml files.

tree.write('output.xml')