Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 529 lines (401 sloc) 16.39 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
===========================
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 CDATA
   9 XInclude and ElementInclude
   10 write_c14n on ElementTree

..
  >>> try: from StringIO import StringIO
  ... except ImportError:
  ... from io import BytesIO
  ... def StringIO(s=None):
  ... if isinstance(s, str): s = s.encode("UTF-8")
  ... return BytesIO(s)

  >>> try: from collections import deque
  ... except ImportError:
  ... class deque(list):
  ... def popleft(self): return self.pop(0)

  >>> try: unicode = __builtins__["unicode"]
  ... except (NameError, KeyError): unicode = str


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:

.. sourcecode:: pycon

  >>> from lxml import etree

..
  >>> import sys
  >>> from lxml import etree as _etree
  >>> if sys.version_info[0] >= 3:
  ... class etree_mock(object):
  ... def __getattr__(self, name): return getattr(_etree, name)
  ... def tostring(self, *args, **kwargs):
  ... s = _etree.tostring(*args, **kwargs)
  ... if isinstance(s, bytes) and bytes([10]) in s: s = s.decode("utf-8") # CR
  ... if s[-1] == '\n': s = s[:-1]
  ... return s
  ... else:
  ... class etree_mock(object):
  ... def __getattr__(self, name): return getattr(_etree, name)
  ... def tostring(self, *args, **kwargs):
  ... s = _etree.tostring(*args, **kwargs)
  ... if s[-1] == '\n': s = s[:-1]
  ... return s
  >>> etree = etree_mock()


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`: element_classes.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:

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

  >>> [ 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']

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 from Python 2.4.

.. sourcecode:: pycon

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

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

.. sourcecode:: pycon

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

..
  >>> etree.clear_error_log()
  >>> try:
  ... etree.parse(StringIO(broken_xml))
  ... except etree.XMLSyntaxError:
  ... import sys; e = sys.exc_info()[1]

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:

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

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

.. sourcecode:: pycon

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

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

.. sourcecode:: pycon

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

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

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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


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:

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

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

.. sourcecode:: pycon

  >>> f = StringIO('<a><b/></a>')
  >>> tree = etree.parse(f)
  >>> f2 = StringIO()
  >>> tree.write_c14n(f2)
  >>> print(f2.getvalue().decode("utf-8"))
  <a><b></b></a>
Something went wrong with that request. Please try again.