Write Data to XML File using Python

xml.etree.ElementTree module

import xml.etree.ElementTree as elementTree

data = [
    {'id': 1, 'name': 'John'},
    {'id': 2, 'name': 'Mary'},
    {'id': 3, 'name': 'Robert'},
]

persons = elementTree.Element('persons')

for item in data:
    person = elementTree.SubElement(persons, 'person')
    person.set('id', str(item['id']))

    name = elementTree.SubElement(person, 'name')
    name.text = item['name']

tree = elementTree.ElementTree(persons)
tree.write('test.xml', encoding='UTF-8', xml_declaration=True)

Leave a Comment

Cancel reply

Your email address will not be published.