===========================
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`_.

.. _`parsing XML`: parsing.html
.. _`XPath and XSLT`: xpathxslt.html
.. _`validating XML`: validation.html
.. _`SAX-API`: sax.html
.. _`XPath functions in Python`: extensions.html
.. _`Python element classes`: element_classes.html
.. _`at the C-level`: capi.html
.. _`URL resolvers`: resolvers.html
.. _`generated API documentation`: api/index.html


.. contents::
.. 
   1  lxml.etree
   2  Other Element APIs
   3  Trees and Documents
   4  Iteration
   5  Error handling on exceptions
   6  Error logging
   7  Serialisation
   8  XInclude and ElementInclude
   9  write_c14n on ElementTree


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.

.. _`ElementTree API`: http://effbot.org/zone/element-index.htm
.. _`compatibility`:   compatibility.html

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
  >>> from StringIO import StringIO


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.

.. _`custom element subclasses`: namespace_extensions.html
.. _`objectify`: objectify.html
.. _`different lookup schemes`: element_classes.html#setting-up-a-class-lookup-scheme
.. _`Amara bindery`: http://uche.ogbuji.net/tech/4suite/amara/


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
  >>> print etree.tostring(tree)
  <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 ``reversed()`` function
that exists in Python 2.4 and later.

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 an additional ``tag`` keyword argument that
filters the generated elements by tag name::

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

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

.. _`parser documentation`: parsing.html#iterparse-and-iterwalk


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 occured and "might have" lead to the problem from the error log
copy attached to the exception::

  >>> etree.clearErrorLog()
  >>> 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, entry.type_name, entry.filename
  PARSER ERR_TAG_NAME_MISMATCH <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, entry.type_name, entry.filename
  PARSER ERR_TAG_NOT_FINISHED <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
-------------

lxml.etree has direct support for pretty printing XML output.  Functions like
``ElementTree.write()`` and ``tostring()`` support it through a keyword
argument::

  >>> root = etree.XML("<root><test/></root>")
  >>> print etree.tostring(root)
  <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.

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")
  '<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`_.

.. _`Unicode support`: parsing.html#python-unicode-strings

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)
  '<\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):
    ...
  XMLSyntaxError: ...


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.

.. _ElementInclude: http://effbot.org/zone/element-xinclude.htm


write_c14n on ElementTree
-------------------------

The lxml.etree.ElementTree class has a method write_c14n, which takes a file
object as argument.  This file object will receive an UTF-8 representation of
the canonicalized form of the XML, following the W3C C14N recommendation.  For
example::

  >>> f = StringIO('<a><b/></a>')
  >>> tree = etree.parse(f)
  >>> f2 = StringIO()
  >>> tree.write_c14n(f2)
  >>> f2.getvalue()
  '<a><b></b></a>'
