Modifying an XML File

suggest change

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

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')

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents