summaryrefslogtreecommitdiff
path: root/doc/api.txt
blob: 2a085d2f33edc8638fbfcc11e31b91a3da1c60bd (plain)
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
===========================
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   Incremental XML generation
   9   CDATA
   10  XInclude and ElementInclude

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


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 builtin ``reversed()`` function.

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 one (or more, since lxml 3.0) additional
arguments that filter the generated elements by tag name:

.. sourcecode:: pycon

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

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

    >>> from collections import deque
    >>> 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 occurred 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[0])
  <string>:4:8:FATAL:PARSER:ERR_TAG_NAME_MISMATCH: Opening and ending tag mismatch: a line 3 and root

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 ``error_log.last_error`` that returns the
last error or fatal error that occurred, so that it's easy to test if there was
an error at all. Note, however, that there might have been more than one error,
and the first error that occurred might be more relevant in some cases.


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 <https://www.w3.org/TR/xml-exc-c14n/>`_
and `C14N 2.0 <https://www.w3.org/TR/xml-c14n2/>`_.  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.

.. sourcecode:: pycon

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

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

XML declaration
...............

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

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

.. sourcecode:: pycon

  >>> 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 <https://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol>`_::

    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:

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