all Python 3xml.etree.ElementTreefunction
xml.etree.ElementTree.parse()
parsing
Reads XML from a file (a name or a file object) and returns an ElementTree; get the root with getroot().
Syntax
tree = ET.parse(source, parser=None)
root = tree.getroot()
A common slip is mixing it up with fromstring: parse() returns an ElementTree wrapper, while fromstring() returns an Element. The parser takes the encoding from the XML declaration (UTF-8 by default), so pass a file name or a file opened in 'rb' rather than a text stream with some other encoding. parse() loads the whole document into memory; for multi-gigabyte files use iterparse(). For untrusted files use defusedxml.
Examples
import xml.etree.ElementTree as ET
with open('books.xml', 'w', encoding='utf-8') as f:
f.write('<lib><book>Dune</book><book>Solaris</book></lib>')
tree = ET.parse('books.xml')
print(type(tree).__name__) # → ElementTree
root = tree.getroot()
print(root.tag, [b.text for b in root]) # → lib ['Dune', 'Solaris']
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy