Debian Codegraph @

doc/parsing.txt

raw
1 ==============================
2 Parsing XML and HTML with lxml
3 ==============================
4
5 lxml provides a very simple and powerful API for parsing XML and HTML. It
6 supports one-step parsing as well as step-by-step parsing using an
7 event-driven API (currently only for XML).
8
9 .. contents::
10 ..
11 1 Parsers
12 1.1 Parser options
13 1.2 Error log
14 1.3 Parsing HTML
15 1.4 Doctype information
16 2 The target parser interface
17 3 The feed parser interface
18 4 Incremental event parsing
19 4.1 Event types
20 4.2 Modifying the tree
21 4.3 Selective tag events
22 4.4 Comments and PIs
23 4.5 Events with custom targets
24 5 iterparse and iterwalk
25 5.1 iterwalk
26 6 Python unicode strings
27 6.1 Serialising to Unicode strings
28
29
30 The usual setup procedure:
31
32 .. sourcecode:: pycon
33
34 >>> from lxml import etree
35
36 The following examples also use StringIO or BytesIO to show how to parse
37 from files and file-like objects. Both are available in the ``io`` module:
38
39 .. sourcecode:: python
40
41 from io import StringIO, BytesIO
42
43 ..
44 >>> from lxml import usedoctest
45
46 >>> try: from StringIO import StringIO
47 ... except ImportError:
48 ... from io import BytesIO
49 ... def StringIO(s):
50 ... if isinstance(s, str): s = s.encode("UTF-8")
51 ... return BytesIO(s)
52
53 >>> try: unicode = unicode
54 ... except NameError: unicode = str
55
56 >>> import sys
57 >>> from lxml import etree as _etree
58 >>> if sys.version_info[0] >= 3:
59 ... class etree_mock(object):
60 ... def __getattr__(self, name): return getattr(_etree, name)
61 ... def tostring(self, *args, **kwargs):
62 ... s = _etree.tostring(*args, **kwargs)
63 ... if isinstance(s, bytes) and bytes([10]) in s: s = s.decode("utf-8") # CR
64 ... if s[-1] == '\n': s = s[:-1]
65 ... return s
66 ... else:
67 ... class etree_mock(object):
68 ... def __getattr__(self, name): return getattr(_etree, name)
69 ... def tostring(self, *args, **kwargs):
70 ... s = _etree.tostring(*args, **kwargs)
71 ... if s[-1] == '\n': s = s[:-1]
72 ... return s
73 >>> etree = etree_mock()
74
75
76 Parsers
77 =======
78
79 Parsers are represented by parser objects. There is support for parsing both
80 XML and (broken) HTML. Note that XHTML is best parsed as XML, parsing it with
81 the HTML parser can lead to unexpected results. Here is a simple example for
82 parsing XML from an in-memory string:
83
84 .. sourcecode:: pycon
85
86 >>> xml = '<a xmlns="test"><b xmlns="test"/></a>'
87
88 >>> root = etree.fromstring(xml)
89 >>> etree.tostring(root)
90 b'<a xmlns="test"><b xmlns="test"/></a>'
91
92 To read from a file or file-like object, you can use the ``parse()`` function,
93 which returns an ``ElementTree`` object that wraps the document root:
94
95 .. sourcecode:: pycon
96
97 >>> tree = etree.parse(StringIO(xml))
98 >>> etree.tostring(tree.getroot())
99 b'<a xmlns="test"><b xmlns="test"/></a>'
100
101 Note how the ``parse()`` function reads from a file-like object here. If
102 parsing is done from a real file, it is more common (and also somewhat more
103 efficient) to pass a filename:
104
105 .. sourcecode:: pycon
106
107 >>> tree = etree.parse("doc/test.xml")
108
109 lxml can parse from a local file, an HTTP URL or an FTP URL. It also
110 auto-detects and reads gzip-compressed XML files (.gz, zlib).
111
112 As of lxml 6.0, however, HTTP, FTP and zlib support have become optional features
113 that can be enabled and disabled at compile time in libxml2.
114 This was changed because both HTTP and FTP are considered insecure protocols and
115 automatic decompression without user interaction allows for compression bombs,
116 i.e. very large parser input resulting from highly compressed input data.
117 Test for e.g. ``"zlib" in getattr(etree, 'LIBXML_FEATURES', ["zlib"])`` to see
118 if a feature is available in a given lxml installation.
119 Otherwise, you can resort at runtime to other (usually slower) Python tools for
120 passing decompressed input into lxml or reading from the network.
121
122 If you want to parse from a string (bytes or text) and still provide a base URL
123 for the document (e.g. to support relative paths in an XInclude), you can pass
124 the ``base_url`` keyword argument:
125
126 .. sourcecode:: pycon
127
128 >>> root = etree.fromstring(xml, base_url="http://where.it/is/from.xml")
129
130
131 Parser options
132 --------------
133
134 The parsers accept a number of setup options as keyword arguments. The above
135 example is easily extended to clean up namespaces during parsing:
136
137 .. sourcecode:: pycon
138
139 >>> parser = etree.XMLParser(ns_clean=True)
140 >>> xml_root = etree.fromstring(xml, parser)
141 >>> etree.tostring(xml_root)
142 b'<a xmlns="test"><b/></a>'
143
144 The keyword arguments in the constructor are mainly based on the libxml2
145 parser configuration. A DTD will also be loaded if validation or attribute
146 default values are requested.
147
148 Available boolean keyword arguments:
149
150 * attribute_defaults - read the DTD (if referenced by the document) and add
151 the default attributes from it
152
153 * dtd_validation - validate while parsing (if a DTD was referenced)
154
155 * load_dtd - load and parse the DTD while parsing (no validation is performed)
156
157 * no_network - prevent network access when looking up external
158 documents (on by default)
159
160 * ns_clean - try to clean up redundant namespace declarations
161
162 * recover - try hard to parse through broken XML
163
164 * remove_blank_text - discard blank text nodes between tags, also known as
165 ignorable whitespace. This is best used together with a DTD or schema
166 (which tells data and noise apart), otherwise a heuristic will be applied.
167
168 * remove_comments - discard comments
169
170 * remove_pis - discard processing instructions
171
172 * strip_cdata - replace CDATA sections by normal text content (on by
173 default)
174
175 * resolve_entities - replace entities by their text value (on by
176 default)
177
178 * huge_tree - disable security restrictions and support very deep trees
179 and very long text content (only affects libxml2 2.7+)
180
181 * compact - use compact storage for short text content (on by default)
182
183 * collect_ids - collect XML IDs in a hash table while parsing (on by default).
184 Disabling this can substantially speed up parsing of documents with many
185 different IDs if the hash lookup is not used afterwards.
186
187 Other keyword arguments:
188
189 * encoding - override the document encoding
190
191 * target - a parser target object that will receive the parse events
192 (see `The target parser interface`_)
193
194 * schema - an XMLSchema to validate against (see `validation <validation.html#xmlschema>`_)
195
196
197 Error log
198 ---------
199
200 Parsers have an ``error_log`` property that lists the errors and
201 warnings of the last parser run:
202
203 .. sourcecode:: pycon
204
205 >>> parser = etree.XMLParser()
206 >>> print(len(parser.error_log))
207 0
208
209 >>> tree = etree.XML("<root>\n</b>", parser) # doctest: +ELLIPSIS
210 Traceback (most recent call last):
211 ...
212 lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: root line 1 and b, line 2, column 5...
213
214 >>> print(len(parser.error_log))
215 1
216
217 >>> error = parser.error_log[0]
218 >>> print(error.message)
219 Opening and ending tag mismatch: root line 1 and b
220 >>> print(error.line)
221 2
222 >>> print(error.column)
223 5
224
225 Each entry in the log has the following properties:
226
227 * ``message``: the message text
228 * ``domain``: the domain ID (see the lxml.etree.ErrorDomains class)
229 * ``type``: the message type ID (see the lxml.etree.ErrorTypes class)
230 * ``level``: the log level ID (see the lxml.etree.ErrorLevels class)
231 * ``line``: the line at which the message originated (if applicable)
232 * ``column``: the character column at which the message originated (if applicable)
233 * ``filename``: the name of the file in which the message originated (if applicable)
234
235 For convenience, there are also three properties that provide readable
236 names for the ID values:
237
238 * ``domain_name``
239 * ``type_name``
240 * ``level_name``
241
242 To filter for a specific kind of message, use the different
243 ``filter_*()`` methods on the error log (see the
244 lxml.etree._ListErrorLog class).
245
246
247 Parsing HTML
248 ------------
249
250 HTML parsing is similarly simple. The parsers have a ``recover``
251 keyword argument that the HTMLParser sets by default. It lets libxml2
252 try its best to return a valid HTML tree with all content it can
253 manage to parse. It will not raise an exception on parser errors.
254 You should use libxml2 version 2.6.21 or newer to take advantage of
255 this feature.
256
257 .. sourcecode:: pycon
258
259 >>> broken_html = "<html><head><title>test</title><body><h1>page title</h3>"
260
261 >>> parser = etree.HTMLParser()
262 >>> html_root = etree.fromstring(broken_html, parser)
263
264 >>> result = etree.tostring(html_root,
265 ... pretty_print=True, method="html")
266 >>> print(result)
267 <html>
268 <head>
269 <title>test</title>
270 </head>
271 <body>
272 <h1>page title</h1>
273 </body>
274 </html>
275
276 As a nicer alias for parsing HTML literals, lxml has an ``HTML()`` function,
277 similar to the ``XML()`` shortcut known from ElementTree:
278
279 .. sourcecode:: pycon
280
281 >>> html_root = etree.HTML("""
282 ... <html>
283 ... <body>
284 ... <h1>page title</h1>
285 ... </body>
286 ... </html>
287 ... """)
288
289 Note: The support for parsing broken HTML depends entirely on libxml2's recovery
290 algorithm. It is *not* the fault of lxml if you find documents that are so
291 heavily broken that the parser cannot handle them. There is also no guarantee
292 that the resulting tree will contain all data from the original document. The
293 parser may have to drop seriously broken parts when struggling to keep
294 parsing. Especially misplaced meta tags can suffer from this, which may lead
295 to encoding problems.
296
297 Note that the result is a valid HTML tree, but it may not be a
298 well-formed XML tree. For example, XML forbids double hyphens in
299 comments, which the HTML parser will happily accept in recovery mode.
300 Therefore, if your goal is to serialise an HTML document as an
301 XML/XHTML document after parsing, you may have to apply some manual
302 preprocessing first.
303
304 Also note that the HTML parser is meant to parse HTML documents. For
305 XHTML documents, use the XML parser, which is namespace aware.
306
307
308 Doctype information
309 -------------------
310
311 The use of the libxml2 parsers makes some additional information available at
312 the API level. Currently, ElementTree objects can access the DOCTYPE
313 information provided by a parsed document, as well as the XML version and the
314 original encoding. Since lxml 3.5, the doctype references are mutable.
315
316 .. sourcecode:: pycon
317
318 >>> pub_id = "-//W3C//DTD XHTML 1.0 Transitional//EN"
319 >>> sys_url = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
320 >>> doctype_string = '<!DOCTYPE html PUBLIC "%s" "%s">' % (pub_id, sys_url)
321 >>> xml_header = '<?xml version="1.0" encoding="ascii"?>'
322 >>> xhtml = xml_header + doctype_string + '<html><body></body></html>'
323
324 >>> tree = etree.parse(StringIO(xhtml))
325 >>> docinfo = tree.docinfo
326 >>> print(docinfo.public_id)
327 -//W3C//DTD XHTML 1.0 Transitional//EN
328 >>> print(docinfo.system_url)
329 http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
330 >>> docinfo.doctype == doctype_string
331 True
332
333 >>> print(docinfo.xml_version)
334 1.0
335 >>> print(docinfo.encoding)
336 ascii
337
338 >>> docinfo.system_url = None
339 >>> docinfo.public_id = None
340 >>> print(etree.tostring(tree))
341 <!DOCTYPE html>
342 <html><body/></html>
343
344
345 The target parser interface
346 ===========================
347
348 .. _`As in ElementTree`: http://effbot.org/elementtree/elementtree-xmlparser.htm
349
350 `As in ElementTree`_, and similar to a SAX event handler, you can pass
351 a target object to the parser:
352
353 .. sourcecode:: pycon
354
355 >>> class EchoTarget(object):
356 ... def start(self, tag, attrib):
357 ... print("start %s %r" % (tag, dict(attrib)))
358 ... def end(self, tag):
359 ... print("end %s" % tag)
360 ... def data(self, data):
361 ... print("data %r" % data)
362 ... def comment(self, text):
363 ... print("comment %s" % text)
364 ... def close(self):
365 ... print("close")
366 ... return "closed!"
367
368 >>> parser = etree.XMLParser(target = EchoTarget())
369
370 >>> result = etree.XML("<element>some<!--comment-->text</element>",
371 ... parser)
372 start element {}
373 data 'some'
374 comment comment
375 data 'text'
376 end element
377 close
378
379 >>> print(result)
380 closed!
381
382 It is important for the ``.close()`` method to reset the parser target
383 to a usable state, so that you can reuse the parser as often as you
384 like:
385
386 .. sourcecode:: pycon
387
388 >>> result = etree.XML("<element>some<!--comment-->text</element>",
389 ... parser)
390 start element {}
391 data 'some'
392 comment comment
393 data 'text'
394 end element
395 close
396
397 >>> print(result)
398 closed!
399
400 Starting with lxml 2.3, the ``.close()`` method will also be called in
401 the error case. This diverges from the behaviour of ElementTree, but
402 allows target objects to clean up their state in all situations, so
403 that the parser can reuse them afterwards.
404
405 .. sourcecode:: pycon
406
407 >>> class CollectorTarget(object):
408 ... def __init__(self):
409 ... self.events = []
410 ... def start(self, tag, attrib):
411 ... self.events.append("start %s %r" % (tag, dict(attrib)))
412 ... def end(self, tag):
413 ... self.events.append("end %s" % tag)
414 ... def data(self, data):
415 ... self.events.append("data %r" % data)
416 ... def comment(self, text):
417 ... self.events.append("comment %s" % text)
418 ... def close(self):
419 ... self.events.append("close")
420 ... return "closed!"
421
422 >>> parser = etree.XMLParser(target = CollectorTarget())
423
424 >>> result = etree.XML("<element>some</error>",
425 ... parser) # doctest: +ELLIPSIS
426 Traceback (most recent call last):
427 ...
428 lxml.etree.XMLSyntaxError: Opening and ending tag mismatch...
429
430 >>> for event in parser.target.events:
431 ... print(event)
432 start element {}
433 data 'some'
434 close
435
436 Note that the parser does *not* build a tree when using a parser
437 target. The result of the parser run is whatever the target object
438 returns from its ``.close()`` method. If you want to return an XML
439 tree here, you have to create it programmatically in the target
440 object. An example for a parser target that builds a tree is the
441 ``TreeBuilder``:
442
443 .. sourcecode:: pycon
444
445 >>> parser = etree.XMLParser(target = etree.TreeBuilder())
446
447 >>> result = etree.XML("<element>some<!--comment-->text</element>",
448 ... parser)
449
450 >>> print(result.tag)
451 element
452 >>> print(result[0].text)
453 comment
454
455
456 The feed parser interface
457 =========================
458
459 Since lxml 2.0, the parsers have a feed parser interface that is
460 compatible to the `ElementTree parsers`_. You can use it to feed data
461 into the parser in a controlled step-by-step way.
462
463 In lxml.etree, you can use both interfaces to a parser at the same
464 time: the ``parse()`` or ``XML()`` functions, and the feed parser
465 interface. Both are independent and will not conflict (except if used
466 in conjunction with a parser target object as described above).
467
468 .. _`ElementTree parsers`: http://effbot.org/elementtree/elementtree-xmlparser.htm
469
470 To start parsing with a feed parser, just call its ``feed()`` method
471 to feed it some data.
472
473 .. sourcecode:: pycon
474
475 >>> parser = etree.XMLParser()
476
477 >>> for data in ('<?xml versio', 'n="1.0"?', '><roo', 't><a', '/></root>'):
478 ... parser.feed(data)
479
480 When you are done parsing, you **must** call the ``close()`` method to
481 retrieve the root Element of the parse result document, and to unlock the
482 parser:
483
484 .. sourcecode:: pycon
485
486 >>> root = parser.close()
487
488 >>> print(root.tag)
489 root
490 >>> print(root[0].tag)
491 a
492
493 If you do not call ``close()``, the parser will stay locked and
494 subsequent feeds will keep appending data, usually resulting in a non-well-formed
495 document and an unexpected parser error. So make sure you
496 always close the parser after use, also in the exception case.
497
498 Another way of achieving the same step-by-step parsing is by writing your own
499 file-like object that returns a chunk of data on each ``read()`` call. Where
500 the feed parser interface allows you to actively pass data chunks into the
501 parser, a file-like object passively responds to ``read()`` requests of the
502 parser itself. Depending on the data source, either way may be more natural.
503
504 Note that the feed parser has its own error log called
505 ``feed_error_log``. Errors in the feed parser do not show up in the
506 normal ``error_log`` and vice versa.
507
508 You can also combine the feed parser interface with the target parser:
509
510 .. sourcecode:: pycon
511
512 >>> parser = etree.XMLParser(target = EchoTarget())
513
514 >>> parser.feed("<eleme")
515 >>> parser.feed("nt>some text</elem")
516 start element {}
517 data 'some text'
518 >>> parser.feed("ent>")
519 end element
520
521 >>> result = parser.close()
522 close
523 >>> print(result)
524 closed!
525
526 Again, this prevents the automatic creation of an XML tree and leaves
527 all the event handling to the target object. The ``close()`` method
528 of the parser forwards the return value of the target's ``close()``
529 method.
530
531
532 Incremental event parsing
533 =========================
534
535 In Python 3.4, the ``xml.etree.ElementTree`` package gained an extension
536 to the feed parser interface that is implemented by the ``XMLPullParser``
537 class. It additionally allows processing parse events after each
538 incremental parsing step, by calling the ``.read_events()`` method and
539 iterating over the result. This is most useful for non-blocking execution
540 environments where data chunks arrive one after the other and should be
541 processed as far as possible in each step.
542
543 The same feature is available in lxml 3.3. The basic usage is as follows:
544
545 .. sourcecode:: pycon
546
547 >>> parser = etree.XMLPullParser(events=('start', 'end'))
548
549 >>> def print_events(parser):
550 ... for action, element in parser.read_events():
551 ... print('%s: %s' % (action, element.tag))
552
553 >>> parser.feed('<root>some text')
554 >>> print_events(parser)
555 start: root
556 >>> print_events(parser) # well, no more events, as before ...
557
558 >>> parser.feed('<child><a />')
559 >>> print_events(parser)
560 start: child
561 start: a
562 end: a
563
564 >>> parser.feed('</child></roo')
565 >>> print_events(parser)
566 end: child
567 >>> parser.feed('t>')
568 >>> print_events(parser)
569 end: root
570
571 Just like the normal feed parser, the ``XMLPullParser`` builds a tree in
572 memory (and you should always call the ``.close()`` method when done with
573 parsing):
574
575 .. sourcecode:: pycon
576
577 >>> root = parser.close()
578 >>> etree.tostring(root)
579 b'<root>some text<child><a/></child></root>'
580
581 However, since the parser provides incremental access to that tree,
582 you can explicitly delete content that you no longer need once you
583 have processed it. Read the section on `Modifying the tree`_ below
584 to see what you can do here and what kind of modifications you should
585 avoid.
586
587 In lxml, it is enough to call the ``.read_events()`` method once as
588 the iterator it returns can be reused when new events are available.
589
590 Also, as known from other iterators in lxml, you can pass a ``tag``
591 argument that selects which parse events are returned by the
592 ``.read_events()`` iterator.
593
594
595 Event types
596 -----------
597
598 The parse events are tuples ``(event-type, object)``. The event types
599 supported by ElementTree and lxml.etree are the strings 'start', 'end',
600 'start-ns' and 'end-ns'. The 'start' and 'end' events represent opening
601 and closing elements. They are accompanied by the respective Element
602 instance. By default, only 'end' events are generated, whereas the
603 example above requested the generation of both 'start' and 'end' events.
604
605 The 'start-ns' and 'end-ns' events notify about namespace declarations.
606 They do not come with Elements. Instead, the value of the 'start-ns'
607 event is a tuple ``(prefix, namespaceURI)`` that designates the beginning
608 of a prefix-namespace mapping. The corresponding ``end-ns`` event does
609 not have a value (None). It is common practice to use a list as namespace
610 stack and pop the last entry on the 'end-ns' event.
611
612 .. sourcecode:: pycon
613
614 >>> def print_events(events):
615 ... for action, obj in events:
616 ... if action in ('start', 'end'):
617 ... print("%s: %s" % (action, obj.tag))
618 ... elif action == 'start-ns':
619 ... print("%s: %s" % (action, obj))
620 ... else:
621 ... print(action)
622
623 >>> event_types = ("start", "end", "start-ns", "end-ns")
624 >>> parser = etree.XMLPullParser(event_types)
625 >>> events = parser.read_events()
626
627 >>> parser.feed('<root><element>')
628 >>> print_events(events)
629 start: root
630 start: element
631 >>> parser.feed('text</element><element>text</element>')
632 >>> print_events(events)
633 end: element
634 start: element
635 end: element
636 >>> parser.feed('<empty-element xmlns="http://testns/" />')
637 >>> print_events(events)
638 start-ns: ('', 'http://testns/')
639 start: {http://testns/}empty-element
640 end: {http://testns/}empty-element
641 end-ns
642 >>> parser.feed('</root>')
643 >>> print_events(events)
644 end: root
645
646
647 Modifying the tree
648 ------------------
649
650 You can modify the element and its descendants when handling the
651 'end' event. To save memory, for example, you can remove subtrees
652 that are no longer needed:
653
654 .. sourcecode:: pycon
655
656 >>> parser = etree.XMLPullParser()
657 >>> events = parser.read_events()
658
659 >>> parser.feed('<root><element key="value">text</element>')
660 >>> parser.feed('<element><child /></element>')
661 >>> for action, elem in events:
662 ... print('%s: %d' % (elem.tag, len(elem))) # processing
663 ... elem.clear(keep_tail=True) # delete children
664 element: 0
665 child: 0
666 element: 1
667 >>> parser.feed('<empty-element xmlns="http://testns/" /></root>')
668 >>> for action, elem in events:
669 ... print('%s: %d' % (elem.tag, len(elem))) # processing
670 ... elem.clear(keep_tail=True) # delete children
671 {http://testns/}empty-element: 0
672 root: 3
673
674 >>> root = parser.close()
675 >>> etree.tostring(root)
676 b'<root/>'
677
678 **WARNING**: During the 'start' event, any content of the element,
679 such as the descendants, following siblings or text, is not yet
680 available and should not be accessed. Only attributes are guaranteed
681 to be set. During the 'end' event, the element and its descendants
682 can be freely modified, but its following siblings should not be
683 accessed. During either of the two events, you **must not** modify or
684 move the ancestors (parents) of the current element. You should also
685 avoid moving or discarding the element itself. The golden rule is: do
686 not touch anything that will have to be touched again by the parser
687 later on.
688
689 If you have elements with a long list of children in your XML file and want
690 to save more memory during parsing, you can clean up the preceding siblings
691 of the current element:
692
693 .. sourcecode:: pycon
694
695 >>> for event, element in parser.read_events():
696 ... # ... do something with the element
697 ... element.clear(keep_tail=True) # clean up children
698 ... while element.getprevious() is not None:
699 ... del element.getparent()[0] # clean up preceding siblings
700
701 The ``while`` loop deletes multiple siblings in a row. This is only necessary
702 if you skipped over some of them using the ``tag`` keyword argument.
703 Otherwise, a simple ``if`` should do. The more selective your tag is,
704 however, the more thought you will have to put into finding the right way to
705 clean up the elements that were skipped. Therefore, it is sometimes easier to
706 traverse all elements and do the tag selection by hand in the event handler
707 code.
708
709
710 Selective tag events
711 --------------------
712
713 As an extension over ElementTree, lxml.etree accepts a ``tag`` keyword
714 argument just like ``element.iter(tag)``. This restricts events to a
715 specific tag or namespace:
716
717 .. sourcecode:: pycon
718
719 >>> parser = etree.XMLPullParser(tag="element")
720
721 >>> parser.feed('<root><element key="value">text</element>')
722 >>> parser.feed('<element><child /></element>')
723 >>> parser.feed('<empty-element xmlns="http://testns/" /></root>')
724
725 >>> for action, elem in parser.read_events():
726 ... print("%s: %s" % (action, elem.tag))
727 end: element
728 end: element
729
730 >>> event_types = ("start", "end")
731 >>> parser = etree.XMLPullParser(event_types, tag="{http://testns/}*")
732
733 >>> parser.feed('<root><element key="value">text</element>')
734 >>> parser.feed('<element><child /></element>')
735 >>> parser.feed('<empty-element xmlns="http://testns/" /></root>')
736
737 >>> for action, elem in parser.read_events():
738 ... print("%s: %s" % (action, elem.tag))
739 start: {http://testns/}empty-element
740 end: {http://testns/}empty-element
741
742
743 Comments and PIs
744 ----------------
745
746 As an extension over ElementTree, the ``XMLPullParser`` in lxml.etree
747 also supports the event types 'comment' and 'pi' for the respective
748 XML structures.
749
750 .. sourcecode:: pycon
751
752 >>> event_types = ("start", "end", "comment", "pi")
753 >>> parser = etree.XMLPullParser(event_types)
754
755 >>> parser.feed('<?some pi ?><!-- a comment --><root>')
756 >>> parser.feed('<element key="value">text</element>')
757 >>> parser.feed('<!-- another comment -->')
758 >>> parser.feed('<element>text</element>tail')
759 >>> parser.feed('<empty-element xmlns="http://testns/" />')
760 >>> parser.feed('</root>')
761
762 >>> for action, elem in parser.read_events():
763 ... if action in ('start', 'end'):
764 ... print("%s: %s" % (action, elem.tag))
765 ... elif action == 'pi':
766 ... print("%s: -%s=%s-" % (action, elem.target, elem.text))
767 ... else: # 'comment'
768 ... print("%s: -%s-" % (action, elem.text))
769 pi: -some=pi -
770 comment: - a comment -
771 start: root
772 start: element
773 end: element
774 comment: - another comment -
775 start: element
776 end: element
777 start: {http://testns/}empty-element
778 end: {http://testns/}empty-element
779 end: root
780
781 >>> root = parser.close()
782 >>> print(root.tag)
783 root
784
785
786 Events with custom targets
787 --------------------------
788
789 You can combine the pull parser with a parser target. In that case,
790 it is the target's responsibility to generate event values. Whatever
791 it returns from its ``.start()`` and ``.end()`` methods will be returned
792 by the pull parser as the second item of the parse events tuple.
793
794 .. sourcecode:: pycon
795
796 >>> class Target(object):
797 ... def start(self, tag, attrib):
798 ... print('-> start(%s)' % tag)
799 ... return '>>START: %s<<' % tag
800 ... def end(self, tag):
801 ... print('-> end(%s)' % tag)
802 ... return '>>END: %s<<' % tag
803 ... def close(self):
804 ... print('-> close()')
805 ... return "CLOSED!"
806
807 >>> event_types = ('start', 'end')
808 >>> parser = etree.XMLPullParser(event_types, target=Target())
809
810 >>> parser.feed('<root><child1 /><child2 /></root>')
811 -> start(root)
812 -> start(child1)
813 -> end(child1)
814 -> start(child2)
815 -> end(child2)
816 -> end(root)
817
818 >>> for action, value in parser.read_events():
819 ... print('%s: %s' % (action, value))
820 start: >>START: root<<
821 start: >>START: child1<<
822 end: >>END: child1<<
823 start: >>START: child2<<
824 end: >>END: child2<<
825 end: >>END: root<<
826
827 >>> print(parser.close())
828 -> close()
829 CLOSED!
830
831 As you can see, the event values do not even have to be Element objects.
832 The target is generally free to decide how it wants to create an XML tree
833 or whatever else it wants to make of the parser callbacks. In many cases,
834 however, you will want to make your custom target inherit from the
835 ``TreeBuilder`` class in order to have it build a tree that you can process
836 normally. The ``start()`` and ``.end()`` methods of ``TreeBuilder`` return
837 the Element object that was created, so you can override them and modify
838 the input or output according to your needs. Here is an example that
839 filters attributes before they are being added to the tree:
840
841 .. sourcecode:: pycon
842
843 >>> class AttributeFilter(etree.TreeBuilder):
844 ... def start(self, tag, attrib):
845 ... attrib = dict(attrib)
846 ... if 'evil' in attrib:
847 ... del attrib['evil']
848 ... return super(AttributeFilter, self).start(tag, attrib)
849
850 >>> parser = etree.XMLPullParser(target=AttributeFilter())
851 >>> parser.feed('<root><child1 test="123" /><child2 evil="YES" /></root>')
852
853 >>> for action, element in parser.read_events():
854 ... print('%s: %s(%r)' % (action, element.tag, element.attrib))
855 end: child1({'test': '123'})
856 end: child2({})
857 end: root({})
858
859 >>> root = parser.close()
860
861
862 iterparse and iterwalk
863 ======================
864
865 As known from ElementTree, the ``iterparse()`` utility function
866 returns an iterator that generates parser events for an XML file (or
867 file-like object), while building the tree. You can think of it as
868 a blocking wrapper around the ``XMLPullParser`` that automatically and
869 incrementally reads data from the input file for you and provides a
870 single iterator for them:
871
872 .. sourcecode:: pycon
873
874 >>> xml = '''
875 ... <root>
876 ... <element key='value'>text</element>
877 ... <element>text</element>tail
878 ... <empty-element xmlns="http://testns/" />
879 ... </root>
880 ... '''
881
882 >>> context = etree.iterparse(StringIO(xml))
883 >>> for action, elem in context:
884 ... print("%s: %s" % (action, elem.tag))
885 end: element
886 end: element
887 end: {http://testns/}empty-element
888 end: root
889
890 After parsing, the resulting tree is available through the ``root`` property
891 of the iterator:
892
893 .. sourcecode:: pycon
894
895 >>> context.root.tag
896 'root'
897
898 The other event types can be activated with the ``events`` keyword argument:
899
900 .. sourcecode:: pycon
901
902 >>> events = ("start", "end")
903 >>> context = etree.iterparse(StringIO(xml), events=events)
904 >>> for action, elem in context:
905 ... print("%s: %s" % (action, elem.tag))
906 start: root
907 start: element
908 end: element
909 start: element
910 end: element
911 start: {http://testns/}empty-element
912 end: {http://testns/}empty-element
913 end: root
914
915 ``iterparse()`` also supports the ``tag`` argument for selective event
916 iteration and several other parameters that control the parser setup.
917 The ``tag`` argument can be a single tag or a sequence of tags.
918 You can also use it to parse HTML input by passing ``html=True``.
919
920
921 iterwalk
922 --------
923
924 For convenience, lxml also provides an ``iterwalk()`` function.
925 It behaves exactly like ``iterparse()``, but works on Elements and
926 ElementTrees. Here is an example for a tree parsed by ``iterparse()``:
927
928 .. sourcecode:: pycon
929
930 >>> f = StringIO(xml)
931 >>> context = etree.iterparse(
932 ... f, events=("start", "end"), tag="element")
933
934 >>> for action, elem in context:
935 ... print("%s: %s" % (action, elem.tag))
936 start: element
937 end: element
938 start: element
939 end: element
940
941 >>> root = context.root
942
943 And now we can take the resulting in-memory tree and iterate over it
944 using ``iterwalk()`` to get the exact same events without parsing the
945 input again:
946
947 .. sourcecode:: pycon
948
949 >>> context = etree.iterwalk(
950 ... root, events=("start", "end"), tag="element")
951
952 >>> for action, elem in context:
953 ... print("%s: %s" % (action, elem.tag))
954 start: element
955 end: element
956 start: element
957 end: element
958
959 In order to avoid wasting time on uninteresting parts of the tree, the ``iterwalk``
960 iterator can be instructed to skip over an entire subtree with its
961 ``.skip_subtree()`` method.
962
963 .. sourcecode:: pycon
964
965 >>> root = etree.XML('''
966 ... <root>
967 ... <a> <b /> </a>
968 ... <c />
969 ... </root>
970 ... ''')
971
972 >>> context = etree.iterwalk(root, events=("start", "end"))
973
974 >>> for action, elem in context:
975 ... print("%s: %s" % (action, elem.tag))
976 ... if action == 'start' and elem.tag == 'a':
977 ... context.skip_subtree() # ignore <b>
978 start: root
979 start: a
980 end: a
981 start: c
982 end: c
983 end: root
984
985 Note that ``.skip_subtree()`` only has an effect when handling ``start`` or
986 ``start-ns`` events.
987
988
989 Python unicode strings
990 ======================
991
992 lxml.etree has broader support for Python unicode strings than the ElementTree
993 library. First of all, where ElementTree would raise an exception, the
994 parsers in lxml.etree can handle unicode strings straight away. This is most
995 helpful for XML snippets embedded in source code using the ``XML()``
996 function:
997
998 .. sourcecode:: pycon
999
1000 >>> root = etree.XML( '<test> \uf8d1 + \uf8d2 </test>' )
1001
1002 This requires, however, that unicode strings do not specify a conflicting
1003 encoding themselves and thus lie about their real encoding:
1004
1005 .. sourcecode:: pycon
1006
1007 >>> etree.XML( '<?xml version="1.0" encoding="ASCII"?>\n' +
1008 ... '<test> \uf8d1 + \uf8d2 </test>' )
1009 Traceback (most recent call last):
1010 ...
1011 ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
1012
1013 Similarly, you will get errors when you try the same with HTML data in a
1014 unicode string that specifies a charset in a meta tag of the header. You
1015 should generally avoid converting XML/HTML data to unicode before passing it
1016 into the parsers. It is both slower and error prone.
1017
1018
1019 Serialising to Unicode strings
1020 ------------------------------
1021
1022 To serialize the result, you would normally use the ``tostring()``
1023 module function, which serializes to plain ASCII by default or a
1024 number of other byte encodings if asked for:
1025
1026 .. sourcecode:: pycon
1027
1028 >>> etree.tostring(root)
1029 b'<test> &#63697; + &#63698; </test>'
1030
1031 >>> etree.tostring(root, encoding='UTF-8', xml_declaration=False)
1032 b'<test> \xef\xa3\x91 + \xef\xa3\x92 </test>'
1033
1034 As an extension, lxml.etree recognises the name 'unicode' as an argument
1035 to the encoding parameter to build a Python unicode representation of a tree:
1036
1037 .. sourcecode:: pycon
1038
1039 >>> etree.tostring(root, encoding='unicode')
1040 '<test> \uf8d1 + \uf8d2 </test>'
1041
1042 >>> el = etree.Element("test")
1043 >>> etree.tostring(el, encoding='unicode')
1044 '<test/>'
1045
1046 >>> subel = etree.SubElement(el, "subtest")
1047 >>> etree.tostring(el, encoding='unicode')
1048 '<test><subtest/></test>'
1049
1050 >>> tree = etree.ElementTree(el)
1051 >>> etree.tostring(tree, encoding='unicode')
1052 '<test><subtest/></test>'
1053
1054 The result of ``tostring(encoding='unicode')`` can be treated like any
1055 other Python unicode string and then passed back into the parsers.
1056 However, if you want to save the result to a file or pass it over the
1057 network, you should use ``write()`` or ``tostring()`` with a byte
1058 encoding (typically UTF-8) to serialize the XML. The main reason is
1059 that unicode strings returned by ``tostring(encoding='unicode')`` are
1060 not byte streams and they never have an XML declaration to specify
1061 their encoding. These strings are most likely not parsable by other
1062 XML libraries.
1063
1064 For normal byte encodings, the ``tostring()`` function automatically
1065 adds a declaration as needed that reflects the encoding of the
1066 returned string. This makes it possible for other parsers to
1067 correctly parse the XML byte stream. Note that using ``tostring()``
1068 with UTF-8 is also considerably faster in most cases.