Use ElementTree to add elements and sub-elements

1
2
3
4
5
6
7
8
9
10
11
import xml.etree.ElementTree as ET
 
root = ET.Element('Configuration')
student = ET.SubElement(root, 'student')
ET.SubElement(student, 'name').text = 'A'
ET.SubElement(student, 'years').text = '20'
 
# Test the result
import xml.dom.minidom
dom = xml.dom.minidom.parseString(ET.tostring(root))
print(dom.toprettyxml())

The result is below.

1
2
3
4
5
6
7
<?xml version="1.0" ?>
<Configuration>
    <student>
        <name>A</name>
        <years>20</years>
    </student>
</Configuration>