Write XML to File with Python

The code

#!/usr/bin/env python
 
from lxml import etree as ET
 
root = ET.Element('data')
person = ET.SubElement(root, 'person')
firstname = ET.SubElement(person, 'firstname')
firstname.text = 'George'
lastname = ET.SubElement(person, 'lastname')
lastname.text = 'Karpouzas'
tree = ET.ElementTree(root)
tree.write('output.xml', pretty_print=True, xml_declaration=True)

The output

<data>
  <person>
    <firstname>George</firstname>
    <lastname>Karpouzas</lastname>
  </person>
</data>
Categories: Python Tags: , , ,
%d bloggers like this: