Python Language Manipulating XML Modifying an XML File

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Python Language Question?