Menu

# APIs specific to lxml.etree

lxml.etree tries to follow established APIs wherever possible. Sometimes, however, the need to expose a feature in an easy way led to the invention of a new API. This page describes the major differences and a few additions to the main ElementTree API.

For a complete reference of the API, see the generated API documentation.

Separate pages describe the support for parsing XML, executing XPath and XSLT, validating XML and interfacing with other XML tools through the SAX-API.

lxml is extremely extensible through XPath functions in Python, custom Python element classes, custom URL resolvers and even at the C-level.

Contents

- lxml.etree
- Other Element APIs
- Trees and Documents
- Iteration
- Error handling on exceptions
- Error logging
- Serialisation
  - C14N
  - Pretty printing
  - XML declaration
- Incremental XML generation
- CDATA
- XInclude and ElementInclude

# lxml.etree

lxml.etree tries to follow the ElementTree API wherever it can. There are however some incompatibilities (see compatibility). The extensions are documented here.

If you need to know which version of lxml is installed, you can access the `lxml.etree.LXML_VERSION` attribute to retrieve a version tuple. Note, however, that it did not exist before version 1.0, so you will get an AttributeError in older versions. The versions of libxml2 and libxslt are available through the attributes `LIBXML_VERSION` and `LIBXSLT_VERSION`.

The following examples usually assume this to be executed first:

    >>> from lxml import etree

# Other Element APIs

While lxml.etree itself uses the ElementTree API, it is possible to replace the Element implementation by custom element subclasses. This has been used to implement well-known XML APIs on top of lxml. For example, lxml ships with a data-binding implementation called objectify, which is similar to the Amara bindery tool.

lxml.etree comes with a number of different lookup schemes to customize the mapping between libxml2 nodes and the Element classes used by lxml.etree.

# Trees and Documents

Compared to the original ElementTree API, lxml.etree has an extended tree model. It knows about parents and siblings of elements:

    >>> root = etree.Element("root")
    >>> a = etree.SubElement(root, "a")
    >>> b = etree.SubElement(root, "b")
    >>> c = etree.SubElement(root, "c")
    >>> d = etree.SubElement(root, "d")
    >>> e = etree.SubElement(d,    "e")
    >>> b.getparent() == root
    True
    >>> print(b.getnext().tag)
    c
    >>> print(c.getprevious().tag)
    b

Elements always live within a document context in lxml. This implies that there is also a notion of an absolute document root. You can retrieve an ElementTree for the root node of a document from any of its elements.

    >>> tree = d.getroottree()
    >>> print(tree.getroot().tag)
    root

Note that this is different from wrapping an Element in an ElementTree. You can use ElementTrees to create XML trees with an explicit root node:

    >>> tree = etree.ElementTree(d)
    >>> print(tree.getroot().tag)
    d
    >>> etree.tostring(tree)
    b'<d><e/></d>'

ElementTree objects are serialised as complete documents, including preceding or trailing processing instructions and comments.

All operations that you run on such an ElementTree (like XPath, XSLT, etc.) will understand the explicitly chosen root as root node of a document. They will not see any elements outside the ElementTree. However, ElementTrees do not modify their Elements:

    >>> element = tree.getroot()
    >>> print(element.tag)
    d
    >>> print(element.getparent().tag)
    root
    >>> print(element.getroottree().getroot().tag)
    root

The rule is that all operations that are applied to Elements use either the Element itself as reference point, or the absolute root of the document that contains this Element (e.g. for absolute XPath expressions). All operations on an ElementTree use its explicit root node as reference.

# Iteration

The ElementTree API makes Elements iterable to supports iteration over their children. Using the tree defined above, we get:

    >>> [ child.tag for child in root ]
    ['a', 'b', 'c', 'd']

To iterate in the opposite direction, use the builtin `reversed()` function.

Tree traversal should use the `element.iter()` method:

    >>> [ el.tag for el in root.iter() ]
    ['root', 'a', 'b', 'c', 'd', 'e']

lxml.etree also supports this, but additionally features an extended API for iteration over the children, following/preceding siblings, ancestors and descendants of an element, as defined by the respective XPath axis:

    >>> [ child.tag for child in root.iterchildren() ]
    ['a', 'b', 'c', 'd']
    >>> [ child.tag for child in root.iterchildren(reversed=True) ]
    ['d', 'c', 'b', 'a']
    >>> [ sibling.tag for sibling in b.itersiblings() ]
    ['c', 'd']
    >>> [ sibling.tag for sibling in c.itersiblings(preceding=True) ]
    ['b', 'a']
    >>> [ ancestor.tag for ancestor in e.iterancestors() ]
    ['d', 'root']
    >>> [ el.tag for el in root.iterdescendants() ]
    ['a', 'b', 'c', 'd', 'e']

Note how `element.iterdescendants()` does not include the element itself, as opposed to `element.iter()`. The latter effectively implements the 'descendant-or-self' axis in XPath.

All of these iterators support one (or more, since lxml 3.0) additional arguments that filter the generated elements by tag name:

    >>> [ child.tag for child in root.iterchildren('a') ]
    ['a']
    >>> [ child.tag for child in d.iterchildren('a') ]
    []
    >>> [ el.tag for el in root.iterdescendants('d') ]
    ['d']
    >>> [ el.tag for el in root.iter('d') ]
    ['d']
    >>> [ el.tag for el in root.iter('d', 'a') ]
    ['a', 'd']

Note that the order of the elements is determined by the iteration order, which is the document order in most cases (except for preceding siblings and ancestors, where it is the reversed document order). The order of the tag selection arguments is irrelevant, as you can see in the last example.

The most common way to traverse an XML tree is depth-first, which traverses the tree in document order. This is implemented by the `.iter()` method. While there is no dedicated method for breadth-first traversal, it is almost as simple if you use the `collections.deque` type.

    >>> root = etree.XML('<root><a><b/><c/></a><d><e/></d></root>')
    >>> print(etree.tostring(root, pretty_print=True, encoding='unicode'))
    <root>
      <a>
        <b/>
        <c/>
      </a>
      <d>
        <e/>
      </d>
    </root>

    >>> queue = deque([root])
    >>> while queue:
    ...    el = queue.popleft()  # pop next element
    ...    queue.extend(el)      # append its children
    ...    print(el.tag)
    root
    a
    d
    b
    c
    e

See also the section on the utility functions `iterparse()` and `iterwalk()` in the parser documentation.

# Error handling on exceptions

Libxml2 provides error messages for failures, be it during parsing, XPath evaluation or schema validation. The preferred way of accessing them is through the local `error_log` property of the respective evaluator or transformer object. See their documentation for details.

However, lxml also keeps a global error log of all errors that occurred at the application level. Whenever an exception is raised, you can retrieve the errors that occurred and "might have" lead to the problem from the error log copy attached to the exception:

    >>> etree.clear_error_log()
    >>> broken_xml = '''
    ... <root>
    ...   <a>
    ... </root>
    ... '''
    >>> try:
    ...   etree.parse(StringIO(broken_xml))
    ... except etree.XMLSyntaxError, e:
    ...   pass # just put the exception into e

Once you have caught this exception, you can access its `error_log` property to retrieve the log entries or filter them by a specific type, error domain or error level:

    >>> log = e.error_log.filter_from_level(etree.ErrorLevels.FATAL)
    >>> print(log)
    <string>:4:8:FATAL:PARSER:ERR_TAG_NAME_MISMATCH: Opening and ending tag mismatch: a line 3 and root
    <string>:5:1:FATAL:PARSER:ERR_TAG_NOT_FINISHED: Premature end of data in tag root line 2

This might look a little cryptic at first, but it is the information that libxml2 gives you. At least the message at the end should give you a hint what went wrong and you can see that the fatal errors (FATAL) happened during parsing (PARSER) lines 4, column 8 and line 5, column 1 of a string (<string>, or the filename if available). Here, PARSER is the so-called error domain, see `lxml.etree.ErrorDomains` for that. You can get it from a log entry like this:

    >>> entry = log[0]
    >>> print(entry.domain_name)
    PARSER
    >>> print(entry.type_name)
    ERR_TAG_NAME_MISMATCH
    >>> print(entry.filename)
    <string>

There is also a convenience attribute `last_error` that returns the last error or fatal error that occurred:

    >>> entry = e.error_log.last_error
    >>> print(entry.domain_name)
    PARSER
    >>> print(entry.type_name)
    ERR_TAG_NOT_FINISHED
    >>> print(entry.filename)
    <string>

# Error logging

lxml.etree supports logging libxml2 messages to the Python stdlib logging module. This is done through the `etree.PyErrorLog` class. It disables the error reporting from exceptions and forwards log messages to a Python logger. To use it, see the descriptions of the function `etree.useGlobalPythonLog` and the class `etree.PyErrorLog` for help. Note that this does not affect the local error logs of XSLT, XMLSchema, etc.

# Serialisation

## C14N

lxml.etree has support for C14N 1.0 and C14N 2.0. When serialising an XML tree using `ElementTree.write()` or `tostring()`, you can pass the option `method="c14n"` for 1.0 or `method="c14n2"` for 2.0.

Additionally, there is a function `etree.canonicalize()` which can be used to convert serialised XML to its canonical form directly, without creating a tree in memory. By default, it returns the canonical output, but can be directed to write it to a file instead.

    >>> c14n_xml = etree.canonicalize("<root><test z='1' y='2'/></root>")
    >>> print(c14n_xml)
    <root><test y="2" z="1"></test></root>

## Pretty printing

Functions like `ElementTree.write()` and `tostring()` also support pretty printing XML through a keyword argument:

    >>> root = etree.XML("<root><test/></root>")
    >>> etree.tostring(root)
    b'<root><test/></root>'

    >>> print(etree.tostring(root, pretty_print=True))
    <root>
      <test/>
    </root>

Note the newline that is appended at the end when pretty printing the output. It was added in lxml 2.0.

## XML declaration

By default, lxml (just as ElementTree) outputs the XML declaration only if it is required by the standard:

    >>> unicode_root = etree.Element( u"t\u3120st" )
    >>> unicode_root.text = u"t\u0A0Ast"
    >>> etree.tostring(unicode_root, encoding="utf-8")
    b'<t\xe3\x84\xa0st>t\xe0\xa8\x8ast</t\xe3\x84\xa0st>'

    >>> print(etree.tostring(unicode_root, encoding="iso-8859-1"))
    <?xml version='1.0' encoding='iso-8859-1'?>
    <t&#12576;st>t&#2570;st</t&#12576;st>

Also see the general remarks on Unicode support.

You can enable or disable the declaration explicitly by passing another keyword argument for the serialisation:

    >>> print(etree.tostring(root, xml_declaration=True))
    <?xml version='1.0' encoding='ASCII'?>
    <root><test/></root>

    >>> unicode_root.clear()
    >>> etree.tostring(unicode_root, encoding="UTF-16LE",
    ...                              xml_declaration=False)
    b'<\x00t\x00 1s\x00t\x00/\x00>\x00'

Note that a standard compliant XML parser will not consider the last line well-formed XML if the encoding is not explicitly provided somehow, e.g. in an underlying transport protocol:

    >>> notxml = etree.tostring(unicode_root, encoding="UTF-16LE",
    ...                                       xml_declaration=False)
    >>> root = etree.XML(notxml)        #doctest: +ELLIPSIS
    Traceback (most recent call last):
      ...
    lxml.etree.XMLSyntaxError: ...

Since version 2.3, the serialisation can override the internal subset of the document with a user provided DOCTYPE:

    >>> xml = '<!DOCTYPE root>\n<root/>'
    >>> tree = etree.parse(StringIO(xml))

    >>> print(etree.tostring(tree))
    <!DOCTYPE root>
    <root/>

    >>> print(etree.tostring(tree,
    ...     doctype='<!DOCTYPE root SYSTEM "/tmp/test.dtd">'))
    <!DOCTYPE root SYSTEM "/tmp/test.dtd">
    <root/>

The content will be encoded, but otherwise copied verbatim into the output stream. It is therefore left to the user to take care for a correct doctype format, including the name of the root node.

# Incremental XML generation

Since version 3.1, lxml provides an `xmlfile` API for incrementally generating XML using the `with` statement. It's main purpose is to freely and safely mix surrounding elements with pre-built in-memory trees, e.g. to write out large documents that consist mostly of repetitive subtrees (like database dumps). But it can be useful in many cases where memory consumption matters or where XML is naturally generated in sequential steps. Since lxml 3.4.1, there is an equivalent context manager for HTML serialisation called `htmlfile`.

The API can serialise to real files (given as file path or file object), as well as file-like objects, e.g. `io.BytesIO()`. Here is a simple example:

    >>> f = BytesIO()
    >>> with etree.xmlfile(f) as xf:
    ...     with xf.element('abc'):
    ...         xf.write('text')

    >>> print(f.getvalue().decode('utf-8'))
    <abc>text</abc>

`xmlfile()` accepts a file path as first argument, or a file(-like) object, as in the example above. In the first case, it takes care to open and close the file itself, whereas file(-like) objects are not closed by default. This is left to the code that opened them. Since lxml 3.4, however, you can pass the argument `close=True` to make lxml call the object's `.close()` method when exiting the xmlfile context manager.

To insert pre-constructed Elements and subtrees, just pass them into `write()`:

    >>> f = BytesIO()
    >>> with etree.xmlfile(f) as xf:
    ...     with xf.element('abc'):
    ...         with xf.element('in'):
    ...
    ...             for value in '123':
    ...                 # construct a really complex XML tree
    ...                 el = etree.Element('xyz', attr=value)
    ...
    ...                 xf.write(el)
    ...
    ...                 # no longer needed, discard it right away!
    ...                 el = None

    >>> print(f.getvalue().decode('utf-8'))
    <abc><in><xyz attr="1"/><xyz attr="2"/><xyz attr="3"/></in></abc>

It is a common pattern to have one or more nested `element()` blocks, and then build in-memory XML subtrees in a loop (using the ElementTree API, the builder API, XSLT, or whatever) and write them out into the XML file one after the other. That way, they can be removed from memory right after their construction, which can largely reduce the memory footprint of an application, while keeping the overall XML generation easy, safe and correct.

Together with Python coroutines, this can be used to generate XML in an asynchronous, non-blocking fashion, e.g. for a stream protocol like the instant messaging protocol XMPP:

    def writer(out_stream):
        with xmlfile(out_stream) as xf:
            with xf.element('{http://etherx.jabber.org/streams}stream'):
                while True:
                    el = (yield)
                    xf.write(el)
                    xf.flush()

    w = writer(stream)
    next(w)   # start writing (run up to 'yield')

Then, whenever XML elements are available for writing, call

    w.send(element)

And when done:

    w.close()

Note the additional `xf.flush()` call in the example above, which is available since lxml 3.4. Normally, the output stream is buffered to avoid excessive I/O calls. Whenever the internal buffer fills up, its content is written out. In the case above, however, we want to make sure that each message that we write (i.e. each element subtree) is written out immediately, so we flush the content explicitly at the right point.

Alternatively, if buffering is not desired at all, it can be disabled by passing the flag `buffered=False` into `xmlfile()` (also since lxml 3.4).

Here is a similar example using an async coroutine in Py3.5 or later, which is supported since lxml 4.0. The output stream is expected to have methods `async def write(self, data)` and `async def close(self)` in this case.

    async def writer(out_stream, xml_messages):
        async with xmlfile(out_stream) as xf:
            async with xf.element('{http://etherx.jabber.org/streams}stream'):
                 async for el in xml_messages:
                      await xf.write(el)
                      await xf.flush()

    class DummyAsyncOut(object):
        async def write(self, data):
            print(data.decode('utf8'))

        async def close(self):
             pass

    stream = DummyAsyncOut()
    async_writer = writer(stream, async_message_stream)

# CDATA

By default, lxml's parser will strip CDATA sections from the tree and replace them by their plain text content. As real applications for CDATA are rare, this is the best way to deal with this issue.

However, in some cases, keeping CDATA sections or creating them in a document is required to adhere to existing XML language definitions. For these special cases, you can instruct the parser to leave CDATA sections in the document:

    >>> parser = etree.XMLParser(strip_cdata=False)
    >>> root = etree.XML('<root><![CDATA[test]]></root>', parser)
    >>> root.text
    'test'

    >>> etree.tostring(root)
    b'<root><![CDATA[test]]></root>'

Note how the `.text` property does not give any indication that the text content is wrapped by a CDATA section. If you want to make sure your data is wrapped by a CDATA block, you can use the `CDATA()` text wrapper:

    >>> root.text = 'test'

    >>> root.text
    'test'
    >>> etree.tostring(root)
    b'<root>test</root>'

    >>> root.text = etree.CDATA(root.text)

    >>> root.text
    'test'
    >>> etree.tostring(root)
    b'<root><![CDATA[test]]></root>'

# XInclude and ElementInclude

You can let lxml process xinclude statements in a document by calling the xinclude() method on a tree:

    >>> data = StringIO('''\
    ... <doc xmlns:xi="http://www.w3.org/2001/XInclude">
    ... <foo/>
    ... <xi:include href="doc/test.xml" />
    ... </doc>''')

    >>> tree = etree.parse(data)
    >>> tree.xinclude()
    >>> print(etree.tostring(tree.getroot()))
    <doc xmlns:xi="http://www.w3.org/2001/XInclude">
    <foo/>
    <a xml:base="doc/test.xml"/>
    </doc>

Note that the ElementTree compatible ElementInclude module is also supported as `lxml.ElementInclude`. It has the additional advantage of supporting custom URL resolvers at the Python level. The normal XInclude mechanism cannot deploy these. If you need ElementTree compatibility or custom resolvers, you have to stick to the external Python module.