How to read a XML file?

The builtin module xml parses XML files. It contains several XML parsers. They all produce a tree of element objects for each tag that can be searched and allow access to attributes.

The following code parses the XML file hamlet.xml:


from xml.dom.minidom import parse

document = parse('hamlet.xml')

actors = document.getElementsByTagName("actor")
for act in actors:
    name = act.getAttribute('name')
    for node in act.childNodes:
        if node.nodeType == node.TEXT_NODE:
            print("{} - {}".format(name, node.data))

How to write a XML file?

You can create a tree of elements from scratch and write it to a XML file:


import xml.etree.ElementTree as ET

data = ET.Element('play')
 
# add subtags with attributes
actors = ET.SubElement(data, 'actors')
 
ham = ET.SubElement(actors, 'actor')
ham.set('name', 'Hamlet')
ham.text = "Hamlet, the Prince of Denmark"

oph = ET.SubElement(actors, 'actress')
oph.set('name', 'Ophelia')
oph.text = "Ophelia"
 
# write as a binary string
with open("actors.xml", "wb") as f:
    f.write(ET.tostring(data))