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

6.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, nsmap=None )
element

An Element instance to be used as the root element.

file

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' )

nsmap

If your document contains multiple XML namespaces, you can supply a dictionary that defines the namespace prefixes you would like to use when this document is converted to XML.

In this dictionary, the keys are namespace prefixes, and each corresponding value is the URI of that namespace. Use None as the key to define the blank namespace's URI.

Here is an example of creation of a document with such a dictionary:

HTML_NS  =  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
XSL_NS   =  "http://www.w3.org/1999/XSL/Transform"
EXSL_NS  =  "http://exslt.org/common"
NS_MAP = {
    None:    HTML_NS,
    "xsl":   XSL_NS,
    "exsl":  EXSL_NS }
rootName = '{%s}%s' % (XSL_NS, 'stylesheet' )
root = etree.Element ( rootName )
sheet = etree.ElementTree ( root, nsmap=NS_MAP )

When this root element is serialized into XML, it will look something like this:

<xsl:stylesheet
    xmlns="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
    xmlns:exsl="http://exslt.org/common"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

Exceptions that can be raised by this constructor include:

IOError

If the file is nonexistent or unreadable.

etree.XMLSyntaxError

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
>>>