Next / Previous / Contents / TCC Help System / NM Tech homepage

7.3. The ElementTree() constructor

To create a new, empty document, use this constructor. It returns a new ElementTree instance.

etree.ElementTree(element=None, file=None)

An Element instance to be used as the root element.


To construct an ElementTree that represents an existing file, pass either a writeable file object, or a string containing the name of the file. Do not use the element argument; if you do, the file argument will be ignored.

For example, to transform a file named balrog.xml into an ElementTree, use this statement:

balrogTree = etree.ElementTree(file='balrog.xml')

Exceptions that can be raised by this constructor include:


If the file is nonexistent or unreadable.


If the file is readable, but its contents are not well-formed XML.

The returned exception value has an .error_log attribute that you can display to find out where in the file errors occurred. Here is an example:

>>> try:
...   bad = etree.fromstring("<a>\n<<oops>\n</a>")
... except etree.XMLSyntaxError, detail:
...   pass
>>> detail
<etree.XMLSyntaxError instance at 0xb7eba10c>
>>> detail.error_log
<string>:2:FATAL:PARSER:ERR_NAME_REQUIRED: StartTag: invalid element name
<string>:3:FATAL:PARSER:ERR_TAG_NAME_MISMATCH: Opening and ending tag mismatch: oops line 2 and a
<string>:3:FATAL:PARSER:ERR_TAG_NOT_FINISHED: Premature end of data in tag a line 1