Debian Codegraph @

doc/api.txt

raw
1 ===========================
2 APIs specific to lxml.etree
3 ===========================
4
5 lxml.etree tries to follow established APIs wherever possible. Sometimes,
6 however, the need to expose a feature in an easy way led to the invention of a
7 new API. This page describes the major differences and a few additions to the
8 main ElementTree API.
9
10 For a complete reference of the API, see the `generated API
11 documentation`_.
12
13 Separate pages describe the support for `parsing XML`_, executing `XPath and
14 XSLT`_, `validating XML`_ and interfacing with other XML tools through the
15 `SAX-API`_.
16
17 lxml is extremely extensible through `XPath functions in Python`_, custom
18 `Python element classes`_, custom `URL resolvers`_ and even `at the C-level`_.
19
20 .. _`parsing XML`: parsing.html
21 .. _`XPath and XSLT`: xpathxslt.html
22 .. _`validating XML`: validation.html
23 .. _`SAX-API`: sax.html
24 .. _`XPath functions in Python`: extensions.html
25 .. _`Python element classes`: element_classes.html
26 .. _`at the C-level`: capi.html
27 .. _`URL resolvers`: resolvers.html
28 .. _`generated API documentation`: api/index.html
29
30
31 .. contents::
32 ..
33 1 lxml.etree
34 2 Other Element APIs
35 3 Trees and Documents
36 4 Iteration
37 5 Error handling on exceptions
38 6 Error logging
39 7 Serialisation
40 8 Incremental XML generation
41 9 CDATA
42 10 XInclude and ElementInclude
43
44 ..
45 >>> from io import BytesIO
46 >>> def StringIO(s=None):
47 ... if isinstance(s, str): s = s.encode("UTF-8")
48 ... return BytesIO(s)
49
50
51 lxml.etree
52 ----------
53
54 lxml.etree tries to follow the `ElementTree API`_ wherever it can. There are
55 however some incompatibilities (see `compatibility`_). The extensions are
56 documented here.
57
58 .. _`ElementTree API`: http://effbot.org/zone/element-index.htm
59 .. _`compatibility`: compatibility.html
60
61 If you need to know which version of lxml is installed, you can access the
62 ``lxml.etree.LXML_VERSION`` attribute to retrieve a version tuple. Note,
63 however, that it did not exist before version 1.0, so you will get an
64 AttributeError in older versions. The versions of libxml2 and libxslt are
65 available through the attributes ``LIBXML_VERSION`` and ``LIBXSLT_VERSION``.
66
67 The following examples usually assume this to be executed first:
68
69 .. sourcecode:: pycon
70
71 >>> from lxml import etree
72
73 ..
74 >>> import sys
75 >>> from lxml import etree as _etree
76 >>> if sys.version_info[0] >= 3:
77 ... class etree_mock(object):
78 ... def __getattr__(self, name): return getattr(_etree, name)
79 ... def tostring(self, *args, **kwargs):
80 ... s = _etree.tostring(*args, **kwargs)
81 ... if isinstance(s, bytes) and bytes([10]) in s: s = s.decode("utf-8") # CR
82 ... if s[-1] == '\n': s = s[:-1]
83 ... return s
84 ... else:
85 ... class etree_mock(object):
86 ... def __getattr__(self, name): return getattr(_etree, name)
87 ... def tostring(self, *args, **kwargs):
88 ... s = _etree.tostring(*args, **kwargs)
89 ... if s[-1] == '\n': s = s[:-1]
90 ... return s
91 >>> etree = etree_mock()
92
93
94 Other Element APIs
95 ------------------
96
97 While lxml.etree itself uses the ElementTree API, it is possible to replace
98 the Element implementation by `custom element subclasses`_. This has been
99 used to implement well-known XML APIs on top of lxml. For example, lxml ships
100 with a data-binding implementation called `objectify`_, which is similar to
101 the `Amara bindery`_ tool.
102
103 lxml.etree comes with a number of `different lookup schemes`_ to customize the
104 mapping between libxml2 nodes and the Element classes used by lxml.etree.
105
106 .. _`custom element subclasses`: element_classes.html
107 .. _`objectify`: objectify.html
108 .. _`different lookup schemes`: element_classes.html#setting-up-a-class-lookup-scheme
109 .. _`Amara bindery`: http://uche.ogbuji.net/tech/4suite/amara/
110
111
112 Trees and Documents
113 -------------------
114
115 Compared to the original ElementTree API, lxml.etree has an extended tree
116 model. It knows about parents and siblings of elements:
117
118 .. sourcecode:: pycon
119
120 >>> root = etree.Element("root")
121 >>> a = etree.SubElement(root, "a")
122 >>> b = etree.SubElement(root, "b")
123 >>> c = etree.SubElement(root, "c")
124 >>> d = etree.SubElement(root, "d")
125 >>> e = etree.SubElement(d, "e")
126 >>> b.getparent() == root
127 True
128 >>> print(b.getnext().tag)
129 c
130 >>> print(c.getprevious().tag)
131 b
132
133 Elements always live within a document context in lxml. This implies that
134 there is also a notion of an absolute document root. You can retrieve an
135 ElementTree for the root node of a document from any of its elements.
136
137 .. sourcecode:: pycon
138
139 >>> tree = d.getroottree()
140 >>> print(tree.getroot().tag)
141 root
142
143 Note that this is different from wrapping an Element in an ElementTree. You
144 can use ElementTrees to create XML trees with an explicit root node:
145
146 .. sourcecode:: pycon
147
148 >>> tree = etree.ElementTree(d)
149 >>> print(tree.getroot().tag)
150 d
151 >>> etree.tostring(tree)
152 b'<d><e/></d>'
153
154 ElementTree objects are serialised as complete documents, including
155 preceding or trailing processing instructions and comments.
156
157 All operations that you run on such an ElementTree (like XPath, XSLT, etc.)
158 will understand the explicitly chosen root as root node of a document. They
159 will not see any elements outside the ElementTree. However, ElementTrees do
160 not modify their Elements:
161
162 .. sourcecode:: pycon
163
164 >>> element = tree.getroot()
165 >>> print(element.tag)
166 d
167 >>> print(element.getparent().tag)
168 root
169 >>> print(element.getroottree().getroot().tag)
170 root
171
172 The rule is that all operations that are applied to Elements use either the
173 Element itself as reference point, or the absolute root of the document that
174 contains this Element (e.g. for absolute XPath expressions). All operations
175 on an ElementTree use its explicit root node as reference.
176
177
178 Iteration
179 ---------
180
181 The ElementTree API makes Elements iterable to support iteration over their
182 children. Using the tree defined above, we get:
183
184 .. sourcecode:: pycon
185
186 >>> [ child.tag for child in root ]
187 ['a', 'b', 'c', 'd']
188
189 To iterate in the opposite direction, use the builtin ``reversed()`` function.
190
191 Tree traversal should use the ``element.iter()`` method:
192
193 .. sourcecode:: pycon
194
195 >>> [ el.tag for el in root.iter() ]
196 ['root', 'a', 'b', 'c', 'd', 'e']
197
198 lxml.etree also supports this, but additionally features an extended API for
199 iteration over the children, following/preceding siblings, ancestors and
200 descendants of an element, as defined by the respective XPath axis:
201
202 .. sourcecode:: pycon
203
204 >>> [ child.tag for child in root.iterchildren() ]
205 ['a', 'b', 'c', 'd']
206 >>> [ child.tag for child in root.iterchildren(reversed=True) ]
207 ['d', 'c', 'b', 'a']
208 >>> [ sibling.tag for sibling in b.itersiblings() ]
209 ['c', 'd']
210 >>> [ sibling.tag for sibling in c.itersiblings(preceding=True) ]
211 ['b', 'a']
212 >>> [ ancestor.tag for ancestor in e.iterancestors() ]
213 ['d', 'root']
214 >>> [ el.tag for el in root.iterdescendants() ]
215 ['a', 'b', 'c', 'd', 'e']
216
217 Note how ``element.iterdescendants()`` does not include the element
218 itself, as opposed to ``element.iter()``. The latter effectively
219 implements the 'descendant-or-self' axis in XPath.
220
221 All of these iterators support one (or more, since lxml 3.0) additional
222 arguments that filter the generated elements by tag name:
223
224 .. sourcecode:: pycon
225
226 >>> [ child.tag for child in root.iterchildren('a') ]
227 ['a']
228 >>> [ child.tag for child in d.iterchildren('a') ]
229 []
230 >>> [ el.tag for el in root.iterdescendants('d') ]
231 ['d']
232 >>> [ el.tag for el in root.iter('d') ]
233 ['d']
234 >>> [ el.tag for el in root.iter('d', 'a') ]
235 ['a', 'd']
236
237 Note that the order of the elements is determined by the iteration order,
238 which is the document order in most cases (except for preceding siblings
239 and ancestors, where it is the reversed document order). The order of
240 the tag selection arguments is irrelevant, as you can see in the last
241 example.
242
243 The most common way to traverse an XML tree is depth-first, which
244 traverses the tree in document order. This is implemented by the
245 ``.iter()`` method. While there is no dedicated method for
246 breadth-first traversal, it is almost as simple if you use the
247 ``collections.deque`` type.
248
249 .. sourcecode:: pycon
250
251 >>> root = etree.XML('<root><a><b/><c/></a><d><e/></d></root>')
252 >>> print(etree.tostring(root, pretty_print=True, encoding='unicode'))
253 <root>
254 <a>
255 <b/>
256 <c/>
257 </a>
258 <d>
259 <e/>
260 </d>
261 </root>
262
263 >>> from collections import deque
264 >>> queue = deque([root])
265 >>> while queue:
266 ... el = queue.popleft() # pop next element
267 ... queue.extend(el) # append its children
268 ... print(el.tag)
269 root
270 a
271 d
272 b
273 c
274 e
275
276 See also the section on the utility functions ``iterparse()`` and
277 ``iterwalk()`` in the `parser documentation`_.
278
279 .. _`parser documentation`: parsing.html#iterparse-and-iterwalk
280
281
282 Error handling on exceptions
283 ----------------------------
284
285 Libxml2 provides error messages for failures, be it during parsing, XPath
286 evaluation or schema validation. The preferred way of accessing them is
287 through the local ``error_log`` property of the respective evaluator or
288 transformer object. See their documentation for details.
289
290 However, lxml also keeps a global error log of all errors that occurred at the
291 application level. Whenever an exception is raised, you can retrieve the
292 errors that occurred and "might have" led to the problem from the error log
293 copy attached to the exception:
294
295 .. sourcecode:: pycon
296
297 >>> etree.clear_error_log()
298 >>> broken_xml = '''
299 ... <root>
300 ... <a>
301 ... </root>
302 ... '''
303 >>> try:
304 ... etree.parse(StringIO(broken_xml))
305 ... except etree.XMLSyntaxError as e:
306 ... pass # just put the exception into e
307
308 ..
309 >>> etree.clear_error_log()
310 >>> try:
311 ... etree.parse(StringIO(broken_xml))
312 ... except etree.XMLSyntaxError:
313 ... import sys; e = sys.exc_info()[1]
314
315 Once you have caught this exception, you can access its ``error_log`` property
316 to retrieve the log entries or filter them by a specific type, error domain or
317 error level:
318
319 .. sourcecode:: pycon
320
321 >>> log = e.error_log.filter_from_level(etree.ErrorLevels.FATAL)
322 >>> print(log[0])
323 <string>:4:8:FATAL:PARSER:ERR_TAG_NAME_MISMATCH: Opening and ending tag mismatch: a line 3 and root
324
325 This might look a little cryptic at first, but it is the information that
326 libxml2 gives you. At least the message at the end should give you a hint
327 what went wrong and you can see that the fatal errors (FATAL) happened during
328 parsing (PARSER) at line 4, column 8 and line 5, column 1 of a string (<string>,
329 or the filename if available). Here, PARSER is the so-called error domain,
330 see ``lxml.etree.ErrorDomains`` for that. You can get it from a log entry
331 like this:
332
333 .. sourcecode:: pycon
334
335 >>> entry = log[0]
336 >>> print(entry.domain_name)
337 PARSER
338 >>> print(entry.type_name)
339 ERR_TAG_NAME_MISMATCH
340 >>> print(entry.filename)
341 <string>
342
343 There is also a convenience attribute ``error_log.last_error`` that returns the
344 last error or fatal error that occurred, so that it's easy to test if there was
345 an error at all. Note, however, that there might have been more than one error,
346 and the first error that occurred might be more relevant in some cases.
347
348
349 Error logging
350 -------------
351
352 lxml.etree supports logging libxml2 messages to the Python stdlib logging
353 module. This is done through the ``etree.PyErrorLog`` class. It disables the
354 error reporting from exceptions and forwards log messages to a Python logger.
355 To use it, see the descriptions of the function ``etree.useGlobalPythonLog``
356 and the class ``etree.PyErrorLog`` for help. Note that this does not affect
357 the local error logs of XSLT, XMLSchema, etc.
358
359
360 Serialisation
361 -------------
362
363 C14N
364 ....
365
366 lxml.etree has support for `C14N 1.0 <https://www.w3.org/TR/xml-exc-c14n/>`_
367 and `C14N 2.0 <https://www.w3.org/TR/xml-c14n2/>`_. When serialising an XML
368 tree using ``ElementTree.write()`` or ``tostring()``, you can pass the option
369 ``method="c14n"`` for 1.0 or ``method="c14n2"`` for 2.0.
370
371 Additionally, there is a function ``etree.canonicalize()`` which can be used
372 to convert serialised XML to its canonical form directly, without creating
373 a tree in memory. By default, it returns the canonical output, but can be
374 directed to write it to a file instead.
375
376 .. sourcecode:: pycon
377
378 >>> c14n_xml = etree.canonicalize("<root><test z='1' y='2'/></root>")
379 >>> print(c14n_xml)
380 <root><test y="2" z="1"></test></root>
381
382 Pretty printing
383 ...............
384
385 Functions like ``ElementTree.write()`` and ``tostring()`` also support pretty
386 printing XML through a keyword argument:
387
388 .. sourcecode:: pycon
389
390 >>> root = etree.XML("<root><test/></root>")
391 >>> etree.tostring(root)
392 b'<root><test/></root>'
393
394 >>> print(etree.tostring(root, pretty_print=True))
395 <root>
396 <test/>
397 </root>
398
399 Note the newline that is appended at the end when pretty printing the
400 output. It was added in lxml 2.0.
401
402 XML declaration
403 ...............
404
405 By default, lxml (just as ElementTree) outputs the XML declaration only if it
406 is required by the standard:
407
408 .. sourcecode:: pycon
409
410 >>> unicode_root = etree.Element( "t\u3120st" )
411 >>> unicode_root.text = "t\u0A0Ast"
412 >>> etree.tostring(unicode_root, encoding="utf-8")
413 b'<t\xe3\x84\xa0st>t\xe0\xa8\x8ast</t\xe3\x84\xa0st>'
414
415 >>> print(etree.tostring(unicode_root, encoding="iso-8859-1"))
416 <?xml version='1.0' encoding='iso-8859-1'?>
417 <t&#12576;st>t&#2570;st</t&#12576;st>
418
419 Also see the general remarks on `Unicode support`_.
420
421 .. _`Unicode support`: parsing.html#python-unicode-strings
422
423 You can enable or disable the declaration explicitly by passing another
424 keyword argument for the serialisation:
425
426 .. sourcecode:: pycon
427
428 >>> print(etree.tostring(root, xml_declaration=True))
429 <?xml version='1.0' encoding='ASCII'?>
430 <root><test/></root>
431
432 >>> unicode_root.clear()
433 >>> etree.tostring(unicode_root, encoding="UTF-16LE",
434 ... xml_declaration=False)
435 b'<\x00t\x00 1s\x00t\x00/\x00>\x00'
436
437 Note that a standard compliant XML parser will not consider the last line
438 well-formed XML if the encoding is not explicitly provided somehow, e.g. in an
439 underlying transport protocol:
440
441 .. sourcecode:: pycon
442
443 >>> notxml = etree.tostring(unicode_root, encoding="UTF-16LE",
444 ... xml_declaration=False)
445 >>> root = etree.XML(notxml) #doctest: +ELLIPSIS
446 Traceback (most recent call last):
447 ...
448 lxml.etree.XMLSyntaxError: ...
449
450 Since version 2.3, the serialisation can override the internal subset
451 of the document with a user provided DOCTYPE:
452
453 .. sourcecode:: pycon
454
455 >>> xml = '<!DOCTYPE root>\n<root/>'
456 >>> tree = etree.parse(StringIO(xml))
457
458 >>> print(etree.tostring(tree))
459 <!DOCTYPE root>
460 <root/>
461
462 >>> print(etree.tostring(tree,
463 ... doctype='<!DOCTYPE root SYSTEM "/tmp/test.dtd">'))
464 <!DOCTYPE root SYSTEM "/tmp/test.dtd">
465 <root/>
466
467 The content will be encoded, but otherwise copied verbatim into the
468 output stream. It is therefore left to the user to take care for a
469 correct doctype format, including the name of the root node.
470
471
472 Incremental XML generation
473 --------------------------
474
475 Since version 3.1, lxml provides an ``xmlfile`` API for incrementally
476 generating XML using the ``with`` statement. Its main purpose is to
477 freely and safely mix surrounding elements with pre-built in-memory
478 trees, e.g. to write out large documents that consist mostly of
479 repetitive subtrees (like database dumps). But it can be useful in
480 many cases where memory consumption matters or where XML is naturally
481 generated in sequential steps. Since lxml 3.4.1, there is an equivalent
482 context manager for HTML serialisation called ``htmlfile``.
483
484 The API can serialise to real files (given as file path or file
485 object), as well as file-like objects, e.g. ``io.BytesIO()``.
486 Here is a simple example::
487
488 >>> f = BytesIO()
489 >>> with etree.xmlfile(f) as xf:
490 ... with xf.element('abc'):
491 ... xf.write('text')
492
493 >>> print(f.getvalue().decode('utf-8'))
494 <abc>text</abc>
495
496 ``xmlfile()`` accepts a file path as first argument, or a file(-like)
497 object, as in the example above. In the first case, it takes care to
498 open and close the file itself, whereas file(-like) objects are not
499 closed by default. This is left to the code that opened them. Since
500 lxml 3.4, however, you can pass the argument ``close=True`` to make
501 lxml call the object's ``.close()`` method when exiting the xmlfile
502 context manager.
503
504 To insert pre-constructed Elements and subtrees, just pass them
505 into ``write()``::
506
507 >>> f = BytesIO()
508 >>> with etree.xmlfile(f) as xf:
509 ... with xf.element('abc'):
510 ... with xf.element('in'):
511 ...
512 ... for value in '123':
513 ... # construct a really complex XML tree
514 ... el = etree.Element('xyz', attr=value)
515 ...
516 ... xf.write(el)
517 ...
518 ... # no longer needed, discard it right away!
519 ... el = None
520
521 >>> print(f.getvalue().decode('utf-8'))
522 <abc><in><xyz attr="1"/><xyz attr="2"/><xyz attr="3"/></in></abc>
523
524 It is a common pattern to have one or more nested ``element()``
525 blocks, and then build in-memory XML subtrees in a loop (using the
526 ElementTree API, the builder API, XSLT, or whatever) and write them
527 out into the XML file one after the other. That way, they can be
528 removed from memory right after their construction, which can largely
529 reduce the memory footprint of an application, while keeping the
530 overall XML generation easy, safe and correct.
531
532 Together with Python coroutines, this can be used to generate XML
533 in an asynchronous, non-blocking fashion, e.g. for a stream protocol
534 like the instant messaging protocol
535 `XMPP <https://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol>`_::
536
537 def writer(out_stream):
538 with xmlfile(out_stream) as xf:
539 with xf.element('{http://etherx.jabber.org/streams}stream'):
540 while True:
541 el = (yield)
542 xf.write(el)
543 xf.flush()
544
545 w = writer(stream)
546 next(w) # start writing (run up to 'yield')
547
548 Then, whenever XML elements are available for writing, call
549
550 ::
551
552 w.send(element)
553
554 And when done::
555
556 w.close()
557
558 Note the additional ``xf.flush()`` call in the example above, which is
559 available since lxml 3.4. Normally, the output stream is buffered to
560 avoid excessive I/O calls. Whenever the internal buffer fills up, its
561 content is written out. In the case above, however, we want to make
562 sure that each message that we write (i.e. each element subtree) is
563 written out immediately, so we flush the content explicitly at the
564 right point.
565
566 Alternatively, if buffering is not desired at all, it can be disabled
567 by passing the flag ``buffered=False`` into ``xmlfile()`` (also since
568 lxml 3.4).
569
570 Here is a similar example using an async coroutine in Py3.5 or later, which is
571 supported since lxml 4.0. The output stream is expected to have methods
572 ``async def write(self, data)`` and ``async def close(self)`` in this case.
573
574 ::
575
576 async def writer(out_stream, xml_messages):
577 async with xmlfile(out_stream) as xf:
578 async with xf.element('{http://etherx.jabber.org/streams}stream'):
579 async for el in xml_messages:
580 await xf.write(el)
581 await xf.flush()
582
583
584 class DummyAsyncOut(object):
585 async def write(self, data):
586 print(data.decode('utf8'))
587
588 async def close(self):
589 pass
590
591 stream = DummyAsyncOut()
592 async_writer = writer(stream, async_message_stream)
593
594
595 CDATA
596 -----
597
598 By default, lxml's parser will strip CDATA sections from the tree and
599 replace them by their plain text content. As real applications for
600 CDATA are rare, this is the best way to deal with this issue.
601
602 However, in some cases, keeping CDATA sections or creating them in a
603 document is required to adhere to existing XML language definitions.
604 For these special cases, you can instruct the parser to leave CDATA
605 sections in the document:
606
607 .. sourcecode:: pycon
608
609 >>> parser = etree.XMLParser(strip_cdata=False)
610 >>> root = etree.XML('<root><![CDATA[test]]></root>', parser)
611 >>> root.text
612 'test'
613
614 >>> etree.tostring(root)
615 b'<root><![CDATA[test]]></root>'
616
617 Note how the ``.text`` property does not give any indication that the
618 text content is wrapped by a CDATA section. If you want to make sure
619 your data is wrapped by a CDATA block, you can use the ``CDATA()``
620 text wrapper:
621
622 .. sourcecode:: pycon
623
624 >>> root.text = 'test'
625
626 >>> root.text
627 'test'
628 >>> etree.tostring(root)
629 b'<root>test</root>'
630
631 >>> root.text = etree.CDATA(root.text)
632
633 >>> root.text
634 'test'
635 >>> etree.tostring(root)
636 b'<root><![CDATA[test]]></root>'
637
638
639 XInclude and ElementInclude
640 ---------------------------
641
642 You can let lxml process xinclude statements in a document by calling the
643 xinclude() method on a tree:
644
645 .. sourcecode:: pycon
646
647 >>> data = StringIO('''\
648 ... <doc xmlns:xi="http://www.w3.org/2001/XInclude">
649 ... <foo/>
650 ... <xi:include href="doc/test.xml" />
651 ... </doc>''')
652
653 >>> tree = etree.parse(data)
654 >>> tree.xinclude()
655 >>> print(etree.tostring(tree.getroot()))
656 <doc xmlns:xi="http://www.w3.org/2001/XInclude">
657 <foo/>
658 <a xml:base="doc/test.xml"/>
659 </doc>
660
661 Note that the ElementTree compatible ElementInclude_ module is also supported
662 as ``lxml.ElementInclude``. It has the additional advantage of supporting
663 custom `URL resolvers`_ at the Python level. The normal XInclude mechanism
664 cannot deploy these. If you need ElementTree compatibility or custom
665 resolvers, you have to stick to the external Python module.
666
667 .. _ElementInclude: http://effbot.org/zone/element-xinclude.htm