Debian Codegraph @

doc/FAQ.txt

raw
1 =====================================
2 lxml FAQ - Frequently Asked Questions
3 =====================================
4
5 .. meta::
6 :description: Frequently Asked Questions about lxml (FAQ)
7 :keywords: lxml, lxml.etree, FAQ, frequently asked questions
8
9 Frequently asked questions on lxml. See also the notes on compatibility_ to
10 ElementTree_.
11
12 .. _compatibility: compatibility.html
13 .. _ElementTree: http://effbot.org/zone/element-index.htm
14 .. _`build instructions`: build.html
15 .. _`MacOS-X` : build.html#building-lxml-on-macos-x
16
17 .. contents::
18 ..
19 1 General Questions
20 1.1 Is there a tutorial?
21 1.2 Where can I find more documentation about lxml?
22 1.3 What standards does lxml implement?
23 1.4 Who uses lxml?
24 1.5 What is the difference between lxml.etree and lxml.objectify?
25 1.6 How can I make my application run faster?
26 1.7 What about that trailing text on serialised Elements?
27 1.8 How can I find out if an Element is a comment or PI?
28 1.9 How can I map an XML tree into a dict of dicts?
29 1.10 Why does lxml sometimes return 'str' values for text in Python 2?
30 1.11 Why do I get XInclude or DTD lookup failures on some systems but not on others?
31 1.12 How do namespaces work in lxml?
32 2 Installation
33 2.1 Which version of libxml2 and libxslt should I use or require?
34 2.2 Where are the binary builds?
35 2.3 Why do I get errors about missing UCS4 symbols when installing lxml?
36 2.4 My C compiler crashes on installation
37 3 Contributing
38 3.1 Why is lxml not written in Python?
39 3.2 How can I contribute?
40 4 Bugs
41 4.1 My application crashes!
42 4.2 My application crashes on MacOS-X!
43 4.3 I think I have found a bug in lxml. What should I do?
44 4.4 How do I know a bug is really in lxml and not in libxml2?
45 4.5 My application crashes with xmlsec!
46 5 Threading
47 5.1 Can I use threads to concurrently access the lxml API?
48 5.2 Does my program run faster if I use threads?
49 5.3 Would my single-threaded program run faster if I turned off threading?
50 5.4 Why can't I reuse XSLT stylesheets in other threads?
51 5.5 My program crashes when run with mod_python/Pyro/Zope/Plone/...
52 6 Parsing and Serialisation
53 6.1 Why doesn't the ``pretty_print`` option reformat my XML output?
54 6.2 Why can't lxml parse my XML from unicode strings?
55 6.3 Can lxml parse from file objects opened in unicode mode?
56 6.4 What is the difference between str(xslt(doc)) and xslt(doc).write() ?
57 6.5 Why can't I just delete parents or clear the root node in iterparse()?
58 6.6 How do I output null characters in XML text?
59 6.7 Is lxml vulnerable to XML bombs?
60 6.8 How do I configure lxml safely as a web-service endpoint?
61 6.9 How can I sort the attributes?
62 7 XPath and Document Traversal
63 7.1 What are the ``findall()`` and ``xpath()`` methods on Element(Tree)?
64 7.2 Why doesn't ``findall()`` support full XPath expressions?
65 7.3 How can I find out which namespace prefixes are used in a document?
66 7.4 How can I specify a default namespace for XPath expressions?
67 7.5 How can I modify the tree during iteration?
68
69
70 The code examples below use the ``lxml.etree`` module:
71
72 .. sourcecode:: pycon
73
74 >>> from lxml import etree
75
76 ..
77 >>> import sys
78 >>> _etree = etree
79 >>> if sys.version_info[0] >= 3:
80 ... class etree_mock(object):
81 ... def __getattr__(self, name): return getattr(_etree, name)
82 ... def tostring(self, *args, **kwargs):
83 ... s = _etree.tostring(*args, **kwargs)
84 ... if isinstance(s, bytes): s = s.decode("utf-8") # CR
85 ... if s[-1] == '\n': s = s[:-1]
86 ... return s
87 ... else:
88 ... class etree_mock(object):
89 ... def __getattr__(self, name): return getattr(_etree, name)
90 ... def tostring(self, *args, **kwargs):
91 ... s = _etree.tostring(*args, **kwargs)
92 ... if s[-1] == '\n': s = s[:-1]
93 ... return s
94 >>> etree = etree_mock()
95
96
97 General Questions
98 =================
99
100 Is there a tutorial?
101 --------------------
102
103 Read the `lxml.etree Tutorial`_. While this is still work in progress
104 (just as any good documentation), it provides an overview of the most
105 important concepts in ``lxml.etree``. If you want to help out,
106 improving the tutorial is a very good place to start.
107
108 There is also a `tutorial for ElementTree`_ which works for
109 ``lxml.etree``. The documentation of the `extended etree API`_ also
110 contains many examples for ``lxml.etree``. Fredrik Lundh's `element
111 library`_ contains a lot of nice recipes that show how to solve common
112 tasks in ElementTree and lxml.etree. To learn using
113 ``lxml.objectify``, read the `objectify documentation`_.
114
115 John Shipman has written another tutorial called `Python XML
116 processing with lxml`_ that contains lots of examples. Liza Daly
117 wrote a nice article about high-performance aspects when `parsing
118 large files with lxml`_.
119
120 .. _`lxml.etree Tutorial`: tutorial.html
121 .. _`tutorial for ElementTree`: https://web.archive.org/web/20200720191942/https://effbot.org/zone/element.htm
122 .. _`extended etree API`: api.html
123 .. _`objectify documentation`: objectify.html
124 .. _`Python XML processing with lxml`: https://web.archive.org/web/20190522191656/http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/index.html
125 .. _`element library`: https://web.archive.org/web/20200703234431/http://www.effbot.org/zone/element-lib.htm
126 .. _`parsing large files with lxml`: http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
127
128
129 Where can I find more documentation about lxml?
130 -----------------------------------------------
131
132 There is a lot of documentation on the web and also in the Python
133 standard library documentation, as lxml implements the well-known
134 `ElementTree API`_ and tries to follow its documentation as closely as
135 possible. The recipes in Fredrik Lundh's `element library`_ are
136 generally worth taking a look at. There are a couple of issues where
137 lxml cannot keep up compatibility. They are described in the
138 compatibility_ documentation.
139
140 The lxml specific extensions to the API are described by individual
141 files in the ``doc`` directory of the source distribution and on `the
142 web page`_.
143
144 The `generated API documentation`_ is a comprehensive API reference
145 for the lxml package.
146
147 .. _`ElementTree API`: https://web.archive.org/web/20200703191710/http://www.effbot.org/zone/element-index.htm
148 .. _`the web page`: https://lxml.de/#documentation
149 .. _`generated API documentation`: api/index.html
150
151
152 What standards does lxml implement?
153 -----------------------------------
154
155 The compliance to XML Standards depends on the support in libxml2 and libxslt.
156 Here is a quote from `http://xmlsoft.org/ <http://xmlsoft.org/>`_:
157
158 In most cases libxml2 tries to implement the specifications in a relatively
159 strictly compliant way. As of release 2.4.16, libxml2 passed all 1800+ tests
160 from the OASIS XML Tests Suite.
161
162 lxml currently supports libxml2 2.6.20 or later, which has even better
163 support for various XML standards. The important ones are:
164
165 * XML 1.0
166 * HTML 4
167 * XML namespaces
168 * XML Schema 1.0
169 * XPath 1.0
170 * XInclude 1.0
171 * XSLT 1.0
172 * EXSLT
173 * XML catalogs
174 * canonical XML
175 * RelaxNG
176 * xml:id
177 * xml:base
178
179 Support for XML Schema is currently not 100% complete in libxml2, but
180 is definitely very close to compliance. Schematron is supported in
181 two ways, the best being the original ISO Schematron reference
182 implementation via XSLT. libxml2 also supports loading documents
183 through HTTP and FTP.
184
185 For `RelaxNG Compact Syntax <http://relaxng.org/compact-tutorial-20030326.html>`_
186 support, there is a tool called `rnc2rng <http://www.gnosis.cx/download/relax/>`_,
187 written by David Mertz, which you might be able to use from Python. Failing
188 that, `trang <http://code.google.com/p/jing-trang/>`_ is the 'official'
189 command line tool (written in Java) to do the conversion.
190
191
192 Who uses lxml?
193 --------------
194
195 As an XML library, lxml is often used under the hood of in-house
196 server applications, such as web servers or applications that
197 facilitate some kind of content management. Many people who deploy
198 Zope_, Plone_ or Django_ use it together with lxml in the background,
199 without speaking publicly about it. Therefore, it is hard to get an
200 idea of who uses it, and the following list of 'users and projects we
201 know of' is very far from a complete list of lxml's users.
202
203 Also note that the compatibility to the ElementTree library does not
204 require projects to set a hard dependency on lxml - as long as they do
205 not take advantage of lxml's enhanced feature set.
206
207 * `cssutils <http://code.google.com/p/cssutils/source/browse/trunk/examples/style.py?r=917>`_,
208 a CSS parser and toolkit, can be used with ``lxml.cssselect``
209 * `Deliverance <http://www.openplans.org/projects/deliverance/project-home>`_,
210 a content theming tool
211 * `Enfold Proxy 4 <http://www.enfoldsystems.com/Products/Proxy/4>`_,
212 a web server accelerator with on-the-fly XSLT processing
213 * `Inteproxy <http://lists.wald.intevation.org/pipermail/inteproxy-devel/2007-February/000000.html>`_,
214 a secure HTTP proxy
215 * `lwebstring <http://pypi.python.org/pypi/lwebstring>`_,
216 an XML template engine
217 * `openpyxl <https://openpyxl.readthedocs.io/>`_,
218 a library to read/write MS Excel 2007 files
219 * `OpenXMLlib <http://permalink.gmane.org/gmane.comp.python.lxml.devel/3250>`_,
220 a library for handling OpenXML document meta data
221 * `PsychoPy <http://www.psychopy.org/>`_,
222 psychology software in Python
223 * `Pycoon <http://pypi.python.org/pypi/pycoon>`_,
224 a WSGI web development framework based on XML pipelines
225 * `pycsw <http://pycsw.org>`_,
226 an `OGC CSW <http://opengeospatial.org/standards/cat>`_ server implementation written in Python
227 * `PyQuery <http://pypi.python.org/pypi/pyquery>`_,
228 a query framework for XML/HTML, similar to jQuery for JavaScript
229 * `python-docx <http://github.com/mikemaccana/python-docx>`_,
230 a package for handling Microsoft's Word OpenXML format
231 * `Rambler <https://www.rambler.ru/>`_,
232 news aggregator on Runet
233 * `rdfadict <http://pypi.python.org/pypi/rdfadict>`_,
234 an RDFa parser with a simple dictionary-like interface.
235 * `xupdate-processor <http://pypi.python.org/pypi/xupdate-processor>`_,
236 an XUpdate implementation for lxml.etree
237 * `Diazo <http://docs.diazo.org/>`_,
238 an XSLT-under-the-hood web site theming engine
239
240 Zope3 and some of its extensions have good support for lxml:
241
242 * `gocept.lxml <http://pypi.python.org/pypi/gocept.lxml>`_,
243 Zope3 interface bindings for lxml
244 * `z3c.rml <http://pypi.python.org/pypi/z3c.rml>`_,
245 an implementation of ReportLab's RML format
246 * `zif.sedna <http://pypi.python.org/pypi/zif.sedna>`_,
247 an XQuery based interface to the Sedna OpenSource XML database
248
249 And don't miss the quotes by our generally happy_ users_, and other
250 `sites that link to lxml`_. As `Liza Daly`_ puts it: "Many software
251 products come with the pick-two caveat, meaning that you must choose
252 only two: speed, flexibility, or readability. When used carefully,
253 lxml can provide all three."
254
255 .. _Zope: http://www.zope.org/
256 .. _Plone: http://www.plone.org/
257 .. _Django: https://www.djangoproject.com/
258
259 .. _happy: http://thread.gmane.org/gmane.comp.python.lxml.devel/3244/focus=3244
260 .. _users: http://article.gmane.org/gmane.comp.python.lxml.devel/3246
261 .. _`sites that link to lxml`: http://www.google.com/search?as_lq=http:%2F%2Flxml.de%2F
262 .. _`Liza Daly`: http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
263
264
265 What is the difference between lxml.etree and lxml.objectify?
266 -------------------------------------------------------------
267
268 The two modules provide different ways of handling XML. However, objectify
269 builds on top of lxml.etree and therefore inherits most of its capabilities
270 and a large portion of its API.
271
272 * lxml.etree is a generic API for XML and HTML handling. It aims for
273 ElementTree compatibility_ and supports the entire XML infoset. It is well
274 suited for both mixed content and data centric XML. Its generality makes it
275 the best choice for most applications.
276
277 * lxml.objectify is a specialized API for XML data handling in a Python object
278 syntax. It provides a very natural way to deal with data fields stored in a
279 structurally well defined XML format. Data is automatically converted to
280 Python data types and can be manipulated with normal Python operators. Look
281 at the examples in the `objectify documentation`_ to see what it feels like
282 to use it.
283
284 Objectify is not well suited for mixed contents or HTML documents. As it is
285 built on top of lxml.etree, however, it inherits the normal support for
286 XPath, XSLT or validation.
287
288
289 How can I make my application run faster?
290 -----------------------------------------
291
292 lxml.etree is a very fast library for processing XML. There are, however, `a
293 few caveats`_ involved in the mapping of the powerful libxml2 library to the
294 simple and convenient ElementTree API. Not all operations are as fast as the
295 simplicity of the API might suggest, while some use cases can heavily benefit
296 from finding the right way of doing them. The `benchmark page`_ has a
297 comparison to other ElementTree implementations and a number of tips for
298 performance tweaking. As with any Python application, the rule of thumb is:
299 the more of your processing runs in C, the faster your application gets. See
300 also the section on threading_.
301
302 .. _`a few caveats`: performance.html#the-elementtree-api
303 .. _`benchmark page`: performance.html
304 .. _threading: #threading
305
306
307 What about that trailing text on serialised Elements?
308 -----------------------------------------------------
309
310 The ElementTree tree model defines an Element as a container with a tag name,
311 contained text, child Elements and a tail text. This means that whenever you
312 serialise an Element, you will get all parts of that Element:
313
314 .. sourcecode:: pycon
315
316 >>> root = etree.XML("<root><tag>text<child/></tag>tail</root>")
317 >>> print(etree.tostring(root[0]))
318 <tag>text<child/></tag>tail
319
320 Here is an example that shows why not serialising the tail would be
321 even more surprising from an object point of view:
322
323 .. sourcecode:: pycon
324
325 >>> root = etree.Element("test")
326
327 >>> root.text = "TEXT"
328 >>> print(etree.tostring(root))
329 <test>TEXT</test>
330
331 >>> root.tail = "TAIL"
332 >>> print(etree.tostring(root))
333 <test>TEXT</test>TAIL
334
335 >>> root.tail = None
336 >>> print(etree.tostring(root))
337 <test>TEXT</test>
338
339 Just imagine a Python list where you append an item and it doesn't
340 show up when you look at the list.
341
342 The ``.tail`` property is a huge simplification for the tree model as
343 it avoids text nodes to appear in the list of children and makes
344 access to them quick and simple. So this is a benefit in most
345 applications and simplifies many, many XML tree algorithms.
346
347 However, in document-like XML (and especially HTML), the above result can be
348 unexpected to new users and can sometimes require a bit more overhead. A good
349 way to deal with this is to use helper functions that copy the Element without
350 its tail. The ``lxml.html`` package also deals with this in a couple of
351 places, as most HTML algorithms benefit from a tail-free behaviour.
352
353
354 How can I find out if an Element is a comment or PI?
355 ----------------------------------------------------
356
357 .. sourcecode:: pycon
358
359 >>> root = etree.XML("<?my PI?><root><!-- empty --></root>")
360
361 >>> root.tag
362 'root'
363 >>> root.getprevious().tag is etree.PI
364 True
365 >>> root[0].tag is etree.Comment
366 True
367
368
369 How can I map an XML tree into a dict of dicts?
370 -----------------------------------------------
371
372 I'm glad you asked.
373
374 .. sourcecode:: python
375
376 def recursive_dict(element):
377 return element.tag, \
378 dict(map(recursive_dict, element)) or element.text
379
380 Note that this beautiful quick-and-dirty converter expects children
381 to have unique tag names and will silently overwrite any data that
382 was contained in preceding siblings with the same name. For any
383 real-world application of xml-to-dict conversion, you had better
384 write your own, longer version of this.
385
386
387 Why does lxml sometimes return 'str' values for text in Python 2?
388 -----------------------------------------------------------------
389
390 In Python 2, lxml's API returns byte strings for plain ASCII text
391 values, be it for tag names or text in Element content. This is the
392 same behaviour as known from ElementTree. The reasoning is that ASCII
393 encoded byte strings are compatible with Unicode strings in Python 2,
394 but consume less memory (usually by a factor of 2 or 4) and are faster
395 to create because they do not require decoding. Plain ASCII string
396 values are very common in XML, so this optimisation is generally worth
397 it.
398
399 In Python 3, lxml always returns Unicode strings for text and names,
400 as does ElementTree. Since Python 3.3, Unicode strings containing
401 only characters that can be encoded in ASCII or Latin-1 are generally
402 as efficient as byte strings. In older versions of Python 3, the
403 above mentioned drawbacks apply.
404
405
406 Why do I get XInclude or DTD lookup failures on some systems but not on others?
407 -------------------------------------------------------------------------------
408
409 To avoid network access, external resources are first looked up in
410 `XML catalogues <https://www.oasis-open.org/committees/entity/spec.html>`_.
411 Many systems have them installed by default, but some don't.
412 On Linux systems, the default place to look is the index file
413 ``/etc/xml/catalog``, which most importantly provides a mapping from
414 doctype IDs to locally installed DTD files.
415
416 See the `libxml2 catalogue documentation <http://xmlsoft.org/catalog.html>`_
417 for further information.
418
419
420 How do namespaces work in lxml?
421 -------------------------------
422
423 The same as in ElementTree. See the `tutorial <tutorial.html#namespaces>`_.
424
425
426 Installation
427 ============
428
429 Which version of libxml2 and libxslt should I use or require?
430 -------------------------------------------------------------
431
432 It really depends on your application, but the rule of thumb is: more recent
433 versions contain less bugs and provide more features.
434
435 * Do not use the stock libxml2 versions 2.9.11 or 2.9.12. They are incompatible
436 with lxml and lead to excess output on serialisation. For static builds
437 against 2.9.12, lxml automatically downloads a post-release version that
438 contains a work-around.
439
440 * Try to use versions of both libraries that were released together. At least
441 the libxml2 version should not be older than the libxslt version.
442
443 * If you use XML Schema or Schematron which are still under development, the
444 most recent version of libxml2 is usually a good bet.
445
446 * The same applies to XPath, where a substantial number of bugs and memory
447 leaks were fixed over time. If you encounter crashes or memory leaks in
448 XPath applications, try a more recent version of libxml2.
449
450 * For the normal tree handling, however, any libxml2 version starting with
451 2.7.x should do.
452
453 Read the `release notes of libxml2`_ and the `release notes of libxslt`_ to
454 see when (or if) a specific bug has been fixed.
455
456 .. _`release notes of libxml2`: http://xmlsoft.org/news.html
457 .. _`release notes of libxslt`: http://xmlsoft.org/XSLT/news.html
458
459
460 Where are the binary builds?
461 ----------------------------
462
463 We provide binaries for Linux (`manylinux`_), macOS and MS Windows
464 shortly after each source release.
465
466 Thanks to the help by Maximilian Hils and the Appveyor build service,
467 we try to serve the frequent requests for binary builds available
468 for Microsoft Windows in a timely fashion, since users of that platform
469 usually fail to build lxml themselves. Two of the major design issues
470 of this operating system make this non-trivial for its users: the lack
471 of a pre-installed standard C-compiler and the missing package management.
472
473 We currently rely on the `WinLibs project <https://github.com/orgs/winlibs>`_
474 to provide library versions that are buildable on MS Windows. If the library
475 that we use in lxml's Windows binary wheels is outdated, it is probably because
476 they have not updated their repositories yet. Consider filing a ticket on their
477 side and notifying us when a new version is available, so that we can integrate it.
478
479 .. _manylinux: https://www.python.org/dev/peps/pep-0513
480
481
482 Why do I get errors about missing UCS4 symbols when installing lxml?
483 --------------------------------------------------------------------
484
485 You are using a Python installation that was configured for a different
486 internal Unicode representation than the lxml package you are trying to
487 install. CPython versions before 3.3 allowed switching between two types
488 at build time: the 32 bit encoding UCS4 and the 16 bit encoding UCS2.
489 Sadly, both are not compatible, so eggs and other binary distributions
490 can only support the one they were compiled with.
491
492 This means that you have to compile lxml from sources for your system. Note
493 that you do not need Cython for this, the lxml source distribution is directly
494 compilable on both platform types. See the `build instructions`_ on how to do
495 this.
496
497
498 My C compiler crashes on installation
499 -------------------------------------
500
501 lxml consists of a relatively large amount of (Cython) generated C code
502 in a single source module. Compiling this module requires a lot of free
503 memory, usually more than half a GB, which can pose problems especially on
504 shared/cloud build systems.
505
506 If your C compiler crashes while building lxml from sources, consider
507 using one of the binary wheels that we provide. The "manylinux_" binaries
508 should generally work well on most build systems and install substantially
509 faster than a source build.
510
511
512 Contributing
513 ============
514
515 Why is lxml not written in Python?
516 ----------------------------------
517
518 It *almost* is.
519
520 lxml is not written in plain Python, because it interfaces with two C
521 libraries: libxml2 and libxslt. Accessing them at the C-level is
522 required for performance reasons.
523
524 However, to avoid writing plain C-code and caring too much about the
525 details of built-in types and reference counting, lxml is written in
526 Cython_, a superset of the Python language that translates to C-code.
527 Chances are that if you know Python, you can write `code that Cython
528 accepts`_. Again, the C-ish style used in the lxml code is just for
529 performance optimisations. If you want to contribute, don't bother
530 with the details, a Python implementation of your contribution is
531 better than none. And keep in mind that lxml's flexible API often
532 favours an implementation of features in pure Python, without
533 bothering with C-code at all. For example, the ``lxml.html`` package
534 is written entirely in Python.
535
536 Please contact the `mailing list`_ if you need any help.
537
538 .. _Cython: http://cython.org/
539 .. _`code that Cython accepts`: http://docs.cython.org/docs/tutorial.html
540
541
542 How can I contribute?
543 ---------------------
544
545 If you find something that you would like lxml to do (or do better),
546 then please tell us about it on the `mailing list`_. Pull requests
547 on github are always appreciated, especially when accompanied by unit
548 tests and documentation (doctests would be great). See the ``tests``
549 subdirectories in the lxml source tree (below the ``src`` directory)
550 and the ReST_ `text files`_ in the ``doc`` directory.
551
552 We also have a `list of missing features`_ that we would like to
553 implement but didn't due to lack of time. If *you* find the time,
554 patches are very welcome.
555
556 .. _ReST: http://docutils.sourceforge.net/rst.html
557 .. _`text files`: https://github.com/lxml/lxml/tree/master/doc
558 .. _`list of missing features`: https://github.com/lxml/lxml/blob/master/IDEAS.txt
559
560 Besides enhancing the code, there are a lot of places where you can help the
561 project and its user base. You can
562
563 * spread the word and write about lxml. Many users (especially new Python
564 users) have not yet heard about lxml, although our user base is constantly
565 growing. If you write your own blog and feel like saying something about
566 lxml, go ahead and do so. If we think your contribution or criticism is
567 valuable to other users, we may even put a link or a quote on the project
568 page.
569
570 * provide code examples for the general usage of lxml or specific problems
571 solved with lxml. Readable code is a very good way of showing how a library
572 can be used and what great things you can do with it. Again, if we hear
573 about it, we can set a link on the project page.
574
575 * work on the documentation. The web page is generated from a set of ReST_
576 `text files`_. It is meant both as a representative project page for lxml
577 and as a site for documenting lxml's API and usage. If you have questions
578 or an idea how to make it more readable and accessible while you are reading
579 it, please send a comment to the `mailing list`_.
580
581 * enhance the web site. We put some work into making the web site
582 usable, understandable and also easy to find, but there's always
583 things that can be done better. You may notice that we are not
584 top-ranked when searching the web for "Python and XML", so maybe you
585 have an idea how to improve that.
586
587 * help with the tutorial. A tutorial is the most important starting point for
588 new users, so it is important for us to provide an easy to understand guide
589 into lxml. As all documentation, the tutorial is work in progress, so we
590 appreciate every helping hand.
591
592 * improve the docstrings. lxml uses docstrings to support Python's integrated
593 online ``help()`` function. However, sometimes these are not sufficient to
594 grasp the details of the function in question. If you find such a place,
595 you can try to write up a better description and send it to the `mailing
596 list`_.
597
598
599 Bugs
600 ====
601
602 My application crashes!
603 -----------------------
604
605 One of the goals of lxml is "no segfaults", so if there is no clear
606 warning in the documentation that you were doing something potentially
607 harmful, you have found a bug and we would like to hear about it.
608 Please report this bug to the `mailing list`_. See the section on bug
609 reporting to learn how to do that.
610
611 If your application (or e.g. your web container) uses threads, please
612 see the FAQ section on threading_ to check if you touch on one of the
613 potential pitfalls.
614
615 In any case, try to reproduce the problem with the latest versions of
616 libxml2 and libxslt. From time to time, bugs and race conditions are found
617 in these libraries, so a more recent version might already contain a fix for
618 your problem.
619
620 Remember: even if you see lxml appear in a crash stack trace, it is
621 not necessarily lxml that *caused* the crash.
622
623 If you are using the *``xmlsec``* library together with lxml, you have to
624 make sure that both use the same version of libxml2. The binary wheels of
625 lxml statically include a (usually recent) version of libxml2, whereas
626 xmlsec often depends on the systemwide installed libraries. If you get
627 crashes or unexpected behaviour when using both, please make sure that both
628 get to use the same libxml2 version. Anaconda/condaforge/etc. based installations
629 will usually come with matching C libraries. If you use xmlsec with the system
630 libraries, please build lxml from sources against those as well, e.g. by installing
631 the development packages of libxml2 and libxslt and then installing lxml with
632
633 ``python -m pip install --no-binary lxml lxml``
634
635
636 My application crashes on MacOS-X!
637 ----------------------------------
638
639 This was a common problem up to lxml 2.1.x. Since lxml 2.2, the only
640 officially supported way to use it on this platform is through a
641 static build against freshly downloaded versions of libxml2 and
642 libxslt. See the build instructions for `MacOS-X`_.
643
644
645 I think I have found a bug in lxml. What should I do?
646 -----------------------------------------------------
647
648 First, you should look at the `current developer changelog`_ to see if this
649 is a known problem that has already been fixed in the master branch since the
650 release you are using.
651
652 .. _`current developer changelog`: https://github.com/lxml/lxml/blob/master/CHANGES.txt
653
654 Also, the 'crash' section above has some good advice on what to try to see if
655 the problem is really in lxml - and not in your setup. Believe it or not,
656 that happens more often than you might think, especially when old libraries
657 or even multiple library versions are installed.
658
659 You should always try to reproduce the problem with the latest
660 versions of libxml2 and libxslt - and make sure they are used.
661 ``lxml.etree`` can tell you what it runs with:
662
663 .. sourcecode:: python
664
665 import sys
666 from lxml import etree
667
668 print("%-20s: %s" % ('Python', sys.version_info))
669 print("%-20s: %s" % ('lxml.etree', etree.LXML_VERSION))
670 print("%-20s: %s" % ('libxml used', etree.LIBXML_VERSION))
671 print("%-20s: %s" % ('libxml compiled', etree.LIBXML_COMPILED_VERSION))
672 print("%-20s: %s" % ('libxslt used', etree.LIBXSLT_VERSION))
673 print("%-20s: %s" % ('libxslt compiled', etree.LIBXSLT_COMPILED_VERSION))
674
675 If you can figure that the problem is not in lxml but in the
676 underlying libxml2 or libxslt, you can ask right on the respective
677 mailing lists, which may considerably reduce the time to find a fix or
678 work-around. See the next question for some hints on how to do that.
679
680 Otherwise, we would really like to hear about it. Please report it to
681 the `bug tracker`_ or to the `mailing list`_ so that we can fix it.
682 It is very helpful in this case if you can come up with a short code
683 snippet that demonstrates your problem. If others can reproduce and
684 see the problem, it is much easier for them to fix it - and maybe even
685 easier for you to describe it and get people convinced that it really
686 is a problem to fix.
687
688 It is important that you always report the version of lxml, libxml2
689 and libxslt that you get from the code snippet above. If we do not
690 know the library versions you are using, we will ask back, so it will
691 take longer for you to get a helpful answer.
692
693 Since as a user of lxml you are likely a programmer, you might find
694 `this article on bug reports`_ an interesting read.
695
696 .. _`bug tracker`: https://bugs.launchpad.net/lxml/
697 .. _`mailing list`: https://lxml.de/mailinglist/
698 .. _`this article on bug reports`: http://www.chiark.greenend.org.uk/~sgtatham/bugs.html
699
700
701 How do I know a bug is really in lxml and not in libxml2?
702 ---------------------------------------------------------
703
704 A large part of lxml's functionality is implemented by libxml2 and
705 libxslt, so problems that you encounter may be in one or the other.
706 Knowing the right place to ask will reduce the time it takes to fix
707 the problem, or to find a work-around.
708
709 Both libxml2 and libxslt come with their own command line frontends,
710 namely ``xmllint`` and ``xsltproc``. If you encounter problems with
711 XSLT processing for specific stylesheets or with validation for
712 specific schemas, try to run the XSLT with ``xsltproc`` or the
713 validation with ``xmllint`` respectively to find out if it fails there
714 as well. If it does, please report directly to the mailing lists of
715 the respective project, namely:
716
717 * `libxml2 mailing list <http://mail.gnome.org/mailman/listinfo/xml>`_
718 * `libxslt mailing list <http://mail.gnome.org/mailman/listinfo/xslt>`_
719
720 On the other hand, everything that seems to be related to Python code,
721 including custom resolvers, custom XPath functions, etc. is likely
722 outside of the scope of libxml2/libxslt. If you encounter problems
723 here or you are not sure where the problem may come from, please
724 ask on the lxml mailing list first.
725
726 In any case, a good explanation of the problem including some simple
727 test code and some input data will help us (or the libxml2 developers)
728 see and understand the problem, which largely increases your chance of
729 getting help. See the question above for a few hints on what is
730 helpful here.
731
732
733 Threading
734 =========
735
736 Can I use threads to concurrently access the lxml API?
737 ------------------------------------------------------
738
739 Short answer: yes, if you use lxml 2.2 and later.
740
741 Since version 1.1, lxml frees the GIL (Python's global interpreter
742 lock) internally when parsing from disk and memory, as long as you use
743 either the default parser (which is replicated for each thread) or
744 create a parser for each thread yourself. lxml also allows
745 concurrency during validation (RelaxNG and XMLSchema) and XSL
746 transformation. You can share RelaxNG, XMLSchema and XSLT objects
747 between threads.
748
749 While you can also share parsers between threads, this will serialize
750 the access to each of them, so it is better to ``.copy()`` parsers or
751 to just use the default parser if you do not need any special
752 configuration. The same applies to the XPath evaluators, which use an
753 internal lock to protect their prepared evaluation contexts. It is
754 therefore best to use separate evaluator instances in threads.
755
756 Warning: Before lxml 2.2, and especially before 2.1, there were
757 various issues when moving subtrees between different threads, or when
758 applying XSLT objects from one thread to trees parsed or modified in
759 another. If you need code to run with older versions, you should
760 generally avoid modifying trees in other threads than the one it was
761 generated in. Although this should work in many cases, there are
762 certain scenarios where the termination of a thread that parsed a tree
763 can crash the application if subtrees of this tree were moved to other
764 documents. You should be on the safe side when passing trees between
765 threads if you either
766
767 - do not modify these trees and do not move their elements to other
768 trees, or
769
770 - do not terminate threads while the trees they parsed are still in
771 use (e.g. by using a fixed size thread-pool or long-running threads
772 in processing chains)
773
774 Since lxml 2.2, even multi-thread pipelines are supported. However,
775 note that it is more efficient to do all tree work inside one thread,
776 than to let multiple threads work on a tree one after the other. This
777 is because trees inherit state from the thread that created them,
778 which must be maintained when the tree is modified inside another
779 thread.
780
781
782 Does my program run faster if I use threads?
783 --------------------------------------------
784
785 Depends. The best way to answer this is timing and profiling.
786
787 The global interpreter lock (GIL) in Python serializes access to the
788 interpreter, so if the majority of your processing is done in Python
789 code (walking trees, modifying elements, etc.), your gain will be
790 close to zero. The more of your XML processing moves into lxml,
791 however, the higher your gain. If your application is bound by XML
792 parsing and serialisation, or by very selective XPath expressions and
793 complex XSLTs, your speedup on multi-processor machines can be
794 substantial.
795
796 See the question above to learn which operations free the GIL to support
797 multi-threading.
798
799
800 Would my single-threaded program run faster if I turned off threading?
801 ----------------------------------------------------------------------
802
803 Possibly, yes. You can see for yourself by compiling lxml entirely
804 without threading support. Pass the ``--without-threading`` option to
805 setup.py when building lxml from source. You can also build libxml2
806 without pthread support (``--without-pthreads`` option), which may add
807 another bit of performance. Note that this will leave internal data
808 structures entirely without thread protection, so make sure you really
809 do not use lxml outside of the main application thread in this case.
810
811
812 Why can't I reuse XSLT stylesheets in other threads?
813 ----------------------------------------------------
814
815 Since later lxml 2.0 versions, you can do this. There is some
816 overhead involved as the result document needs an additional cleanup
817 traversal when the input document and/or the stylesheet were created
818 in other threads. However, on a multi-processor machine, the gain of
819 freeing the GIL easily covers this drawback.
820
821 If you need even the last bit of performance, consider keeping (a copy
822 of) the stylesheet in thread-local storage, and try creating the input
823 document(s) in the same thread. And do not forget to benchmark your
824 code to see if the increased code complexity is really worth it.
825
826
827 My program crashes when run with mod_python/Pyro/Zope/Plone/...
828 ---------------------------------------------------------------
829
830 These environments can use threads in a way that may not make it obvious when
831 threads are created and what happens in which thread. This makes it hard to
832 ensure lxml's threading support is used in a reliable way. Sadly, if problems
833 arise, they are as diverse as the applications, so it is difficult to provide
834 any generally applicable solution. Also, these environments are so complex
835 that problems become hard to debug and even harder to reproduce in a
836 predictable way. If you encounter crashes in one of these systems, but your
837 code runs perfectly when started by hand, the following gives you a few hints
838 for possible approaches to solve your specific problem:
839
840 * make sure you use recent versions of libxml2, libxslt and lxml. The
841 libxml2 developers keep fixing bugs in each release, and lxml also
842 tries to become more robust against possible pitfalls. So newer
843 versions might already fix your problem in a reliable way. Version
844 2.2 of lxml contains many improvements.
845
846 * make sure the library versions you installed are really used. Do
847 not rely on what your operating system tells you! Print the version
848 constants in ``lxml.etree`` from within your runtime environment to
849 make sure it is the case. This is especially a problem under
850 MacOS-X when newer library versions were installed in addition to
851 the outdated system libraries. Please read the bugs section
852 regarding MacOS-X in this FAQ.
853
854 * if you use ``mod_python``, try setting this option:
855
856 PythonInterpreter main_interpreter
857
858 There was a discussion on the mailing list about this problem:
859
860 http://comments.gmane.org/gmane.comp.python.lxml.devel/2942
861
862 * in a threaded environment, try to initially import ``lxml.etree``
863 from the main application thread instead of doing first-time imports
864 separately in each spawned worker thread. If you cannot control the
865 thread spawning of your web/application server, an import of
866 ``lxml.etree`` in sitecustomize.py or usercustomize.py may still do
867 the trick.
868
869 * compile lxml without threading support by running ``setup.py`` with the
870 ``--without-threading`` option. While this might be slower in certain
871 scenarios on multi-processor systems, it *might* also keep your application
872 from crashing, which should be worth more to you than peak performance.
873 Remember that lxml is fast anyway, so concurrency may not even be worth it.
874
875 * look out for fancy XSLT stuff like foreign document access or
876 passing in subtrees through XSLT variables. This might or might not
877 work, depending on your specific usage. Again, later versions of
878 lxml and libxslt provide safer support here.
879
880 * try copying trees at suspicious places in your code and working with
881 those instead of a tree shared between threads. Note that the
882 copying must happen inside the target thread to be effective, not in
883 the thread that created the tree. Serialising in one thread and
884 parsing in another is also a simple (and fast) way of separating
885 thread contexts.
886
887 * try keeping thread-local copies of XSLT stylesheets, i.e. one per thread,
888 instead of sharing one. Also see the question above.
889
890 * you can try to serialise suspicious parts of your code with explicit thread
891 locks, thus disabling the concurrency of the runtime system.
892
893 * report back on the mailing list to see if there are other ways to work
894 around your specific problems. Do not forget to report the version numbers
895 of lxml, libxml2 and libxslt you are using (see the question on reporting
896 a bug).
897
898 Note that most of these options will degrade performance and/or your
899 code quality. If you are unsure what to do, please ask on the mailing
900 list.
901
902
903 Parsing and Serialisation
904 =========================
905
906 ..
907 making doctest happy:
908
909 >>> try: from StringIO import StringIO
910 ... except ImportError: from io import StringIO # Py3
911 >>> filename = StringIO("<root/>")
912
913
914 Why doesn't the ``pretty_print`` option reformat my XML output?
915 ---------------------------------------------------------------
916
917 Pretty printing (or formatting) an XML document means adding white space to
918 the content. These modifications are harmless if they only impact elements in
919 the document that do not carry (text) data. They corrupt your data if they
920 impact elements that contain data. If lxml cannot distinguish between
921 whitespace and data, it will not alter your data. Whitespace is therefore
922 only added between nodes that do not contain data. This is always the case
923 for trees constructed element-by-element, so no problems should be expected
924 here. For parsed trees, a good way to assure that no conflicting whitespace
925 is left in the tree is the ``remove_blank_text`` option:
926
927 .. sourcecode:: pycon
928
929 >>> parser = etree.XMLParser(remove_blank_text=True)
930 >>> tree = etree.parse(filename, parser)
931
932 This will allow the parser to drop blank text nodes when constructing the
933 tree. If you now call a serialization function to pretty print this tree,
934 lxml can add fresh whitespace to the XML tree to indent it.
935
936 Note that the ``remove_blank_text`` option also uses a heuristic if it
937 has no definite knowledge about the document's ignorable whitespace.
938 It will keep blank text nodes that appear after non-blank text nodes
939 at the same level. This is to prevent document-style XML from losing
940 content.
941
942 The HTMLParser has this structural knowledge built-in, which means that
943 most whitespace that appears between tags in HTML documents will *not*
944 be removed by this option, except in places where it is truly ignorable,
945 e.g. in the page header, between table structure tags, etc. Therefore,
946 it is also safe to use this option with the HTMLParser, as it will keep
947 content like the following intact (i.e. it will not remove the space
948 that separates the two words):
949
950 .. sourcecode:: html
951
952 <p><b>some</b> <em>text</em></p>
953
954 If you want to be sure all blank text is removed from an XML document
955 (or just more blank text than the parser does by itself), you have to
956 use either a DTD to tell the parser which whitespace it can safely
957 ignore, or remove the ignorable whitespace manually after parsing,
958 e.g. by setting all tail text to None:
959
960 .. sourcecode:: python
961
962 for element in root.iter():
963 element.tail = None
964
965 Fredrik Lundh also has a Python-level function for indenting XML by
966 appending whitespace to tags. It can be found on his `element library
967 recipes page <http://effbot.org/zone/element-lib.htm#prettyprint>`_.
968
969
970 Why can't lxml parse my XML from unicode strings?
971 -------------------------------------------------
972
973 First of all, XML is explicitly defined as a stream of bytes. It's not
974 Unicode text. Take a look at the `XML specification`_, it's all about byte
975 sequences and how to map them to text and structure. That leads to rule
976 number one: do not decode your XML data yourself. That's a part of the
977 work of an XML parser, and it does it very well. Just pass it your data as
978 a plain byte stream, it will always do the right thing, by specification.
979
980 This also includes not opening XML files in text mode. Make sure you always
981 use binary mode, or, even better, pass the file path into lxml's ``parse()``
982 function to let it do the file opening, reading and closing itself. This
983 is the most simple and most efficient way to do it.
984
985 That being said, lxml can read Python unicode strings and even tries to
986 support them if libxml2 does not. This is because there is one valid use
987 case for parsing XML from text strings: literal XML fragments in source
988 code.
989
990 However, if the unicode string declares an XML encoding internally
991 (``<?xml encoding="..."?>``), parsing is bound to fail, as this encoding is
992 almost certainly not the real encoding used in Python unicode. The same is
993 true for HTML unicode strings that contain charset meta tags, although the
994 problems may be more subtle here. The libxml2 HTML parser may not be able
995 to parse the meta tags in broken HTML and may end up ignoring them, so even
996 if parsing succeeds, later handling may still fail with character encoding
997 errors. Therefore, parsing HTML from unicode strings is a much saner thing
998 to do than parsing XML from unicode strings.
999
1000 Note that Python uses different encodings for unicode on different platforms,
1001 so even specifying the real internal unicode encoding is not portable between
1002 Python interpreters. Don't do it.
1003
1004 Python unicode strings with XML data that carry encoding information are
1005 broken. lxml will not parse them. You must provide parsable data in a
1006 valid encoding.
1007
1008 .. _`XML specification`: http://www.w3.org/TR/REC-xml/
1009
1010
1011 Can lxml parse from file objects opened in unicode/text mode?
1012 -------------------------------------------------------------
1013
1014 Technically, yes. However, you likely do not want to do that, because
1015 it is extremely inefficient. The text encoding that libxml2 uses
1016 internally is UTF-8, so parsing from a Unicode file means that Python
1017 first reads a chunk of data from the file, then decodes it into a new
1018 buffer, and then copies it into a new unicode string object, just to
1019 let libxml2 make yet another copy while encoding it down into UTF-8
1020 in order to parse it. It's clear that this involves a lot more
1021 recoding and copying than when parsing straight from the bytes that
1022 the file contains.
1023
1024 If you really know the encoding better than the parser (e.g. when
1025 parsing HTML that lacks a content declaration), then instead of passing
1026 an encoding parameter into the file object when opening it, create a
1027 new instance of an XMLParser or HTMLParser and pass the encoding into
1028 its constructor. Afterwards, use that parser for parsing, e.g. by
1029 passing it into the ``etree.parse(file, parser)`` function. Remember
1030 to open the file in binary mode (mode="rb"), or, if possible, prefer
1031 passing the file path directly into ``parse()`` instead of an opened
1032 Python file object.
1033
1034
1035 What is the difference between str(xslt(doc)) and xslt(doc).write() ?
1036 ---------------------------------------------------------------------
1037
1038 The str() implementation of the XSLTResultTree class (a subclass of the
1039 ElementTree class) knows about the output method chosen in the stylesheet
1040 (xsl:output), write() doesn't. If you call write(), the result will be a
1041 normal XML tree serialization in the requested encoding. Calling this method
1042 may also fail for XSLT results that are not XML trees (e.g. string results).
1043
1044 If you call str(), it will return the serialized result as specified by the
1045 XSL transform. This correctly serializes string results to encoded Python
1046 strings and honours ``xsl:output`` options like ``indent``. This almost
1047 certainly does what you want, so you should only use ``write()`` if you are
1048 sure that the XSLT result is an XML tree and you want to override the encoding
1049 and indentation options requested by the stylesheet.
1050
1051
1052 Why can't I just delete parents or clear the root node in iterparse()?
1053 ----------------------------------------------------------------------
1054
1055 The ``iterparse()`` implementation is based on the libxml2 parser. It
1056 requires the tree to be intact to finish parsing. If you delete or modify
1057 parents of the current node, chances are you modify the structure in a way
1058 that breaks the parser. Normally, this will result in a segfault. Please
1059 refer to the `iterparse section`_ of the lxml API documentation to find out
1060 what you can do and what you can't do.
1061
1062 .. _`iterparse section`: parsing.html#iterparse-and-iterwalk
1063
1064
1065 How do I output null characters in XML text?
1066 --------------------------------------------
1067
1068 Don't. What you would produce is not well-formed XML. XML parsers
1069 will refuse to parse a document that contains null characters. The
1070 right way to embed binary data in XML is using a text encoding such as
1071 uuencode or base64.
1072
1073
1074 Is lxml vulnerable to XML bombs?
1075 --------------------------------
1076
1077 This has nothing to do with lxml itself, only with the parser of
1078 libxml2. Since libxml2 version 2.7, the parser imposes hard security
1079 limits on input documents to prevent DoS attacks with forged input
1080 data. Since lxml 2.2.1, you can disable these limits with the
1081 ``huge_tree`` parser option if you need to parse *really* large,
1082 trusted documents. All lxml versions will leave these restrictions
1083 enabled by default.
1084
1085 Note that libxml2 versions of the 2.6 series do not restrict their
1086 parser and are therefore vulnerable to DoS attacks.
1087
1088 Note also that these "hard limits" may still be high enough to
1089 allow for excessive resource usage in a given use case. They are
1090 compile time modifiable, so building your own library versions will
1091 allow you to change the limits to your own needs. Also see the next
1092 question.
1093
1094
1095 How do I use lxml safely as a web-service endpoint?
1096 ---------------------------------------------------
1097
1098 XML based web-service endpoints are generally subject to several
1099 types of attacks if they allow some kind of untrusted input.
1100 From the point of view of the underlying XML tool, the most
1101 obvious attacks try to send a relatively small amount of data
1102 that induces a comparatively large resource consumption on the
1103 receiver side.
1104
1105 First of all, make sure network access is not enabled for the XML
1106 parser that you use for parsing untrusted content and that it is
1107 not configured to load external DTDs. Otherwise, attackers can
1108 try to trick the parser into an attempt to load external resources
1109 that are overly slow or impossible to retrieve, thus wasting time
1110 and other valuable resources on your server such as socket
1111 connections. Note that you can register your own document loader
1112 in lxml, which allows for fine-grained control over any read access
1113 to resources.
1114
1115 Some of the most famous excessive content expansion attacks
1116 use XML entity references. Luckily, entity expansion is mostly
1117 useless for the data commonly sent through web services and
1118 can simply be disabled, which rules out several types of
1119 denial of service attacks at once. This also involves an attack
1120 that reads local files from the server, as XML entities can be
1121 defined to expand into the content of external resources.
1122 Consequently, version 1.2 of the SOAP standard explicitly
1123 disallows entity references in the XML stream.
1124
1125 To disable entity expansion, use an XML parser that is configured
1126 with the option ``resolve_entities=False``. Then, after (or
1127 while) parsing the document, use ``root.iter(etree.Entity)`` to
1128 recursively search for entity references. If it contains any,
1129 reject the entire input document with a suitable error response.
1130 In lxml 3.x, you can also use the new DTD introspection API to
1131 apply your own restrictions on input documents. Since version 5.x,
1132 lxml disables the expansion of external entities (XXE) by default.
1133 If you really want to allow loading external files into XML documents
1134 using this functionality, you have to explicitly set
1135 ``resolve_entities=True``.
1136
1137 Another attack to consider is compression bombs. If you allow
1138 compressed input into your web service, attackers can try to send
1139 well forged highly repetitive and thus very well compressing input
1140 that unpacks into a very large XML document in your server's main
1141 memory, potentially a thousand times larger than the compressed
1142 input data.
1143
1144 As a counter measure, either disable compressed input for your
1145 web server, at least for untrusted sources, or use incremental
1146 parsing with ``iterparse()`` instead of parsing the whole input
1147 document into memory in one shot. That allows you to enforce
1148 suitable limits on the input by applying semantic checks that
1149 detect and prevent an illegitimate use of your service. If
1150 possible, you can also use this to reduce the amount of data
1151 that you need to keep in memory while parsing the document,
1152 thus further reducing the possibility of an attacker to trick
1153 your system into excessive resource usage.
1154
1155 Finally, please be aware that XPath suffers from the same
1156 vulnerability as SQL when it comes to content injection. The
1157 obvious fix is to not build any XPath expressions via string
1158 formatting or concatenation when the parameters may come from
1159 untrusted sources, and instead use XPath variables, which
1160 safely expose their values to the evaluation engine.
1161
1162 The defusedxml_ package comes with an example setup and a wrapper
1163 API for lxml that applies certain counter measures internally.
1164
1165 .. _defusedxml: https://github.com/tiran/defusedxml
1166
1167
1168 How can I sort the attributes?
1169 ------------------------------
1170
1171 lxml preserves the order in which attributes were originally created.
1172 There is one case in which this is difficult: when attributes are passed
1173 in a dict or as keyword arguments to the `Element()` factory. Before Python
1174 3.6, dicts had no predictable order.
1175 Since Python 3.6, however, dicts also preserve the creation order of their keys,
1176 and lxml makes use of that since release 4.4.
1177 In earlier versions, lxml tries to assure at least reproducible output by
1178 sorting the attributes from the dict before creating them. All sequential
1179 ways to set attributes keep their order and do not apply sorting. Also,
1180 OrderedDict instances are recognised and not sorted.
1181
1182 In cases where you cannot control the order in which attributes are created,
1183 you can still change it before serialisation. To sort them by name, for example,
1184 you can apply the following function:
1185
1186 .. sourcecode:: python
1187
1188 def sort_attributes(root):
1189 for el in root.iter():
1190 attrib = el.attrib
1191 if len(attrib) > 1:
1192 attributes = sorted(attrib.items())
1193 attrib.clear()
1194 attrib.update(attributes)
1195
1196
1197 XPath and Document Traversal
1198 ============================
1199
1200 What are the ``findall()`` and ``xpath()`` methods on Element(Tree)?
1201 --------------------------------------------------------------------
1202
1203 ``findall()`` is part of the original `ElementTree API`_. It supports a
1204 `simple subset of the XPath language`_, without predicates, conditions and
1205 other advanced features. It is very handy for finding specific tags in a
1206 tree. Another important difference is namespace handling, which uses the
1207 ``{namespace}tagname`` notation. This is not supported by XPath. The
1208 findall, find and findtext methods are compatible with other ElementTree
1209 implementations and allow writing portable code that runs on ElementTree,
1210 cElementTree and lxml.etree.
1211
1212 ``xpath()``, on the other hand, supports the complete power of the XPath
1213 language, including predicates, XPath functions and Python extension
1214 functions. The syntax is defined by the `XPath specification`_. If you need
1215 the expressiveness and selectivity of XPath, the ``xpath()`` method, the
1216 ``XPath`` class and the ``XPathEvaluator`` are the best choice_.
1217
1218 .. _`simple subset of the XPath language`: http://effbot.org/zone/element-xpath.htm
1219 .. _`XPath specification`: http://www.w3.org/TR/xpath
1220 .. _choice: performance.html#xpath
1221
1222
1223 Why doesn't ``findall()`` support full XPath expressions?
1224 ---------------------------------------------------------
1225
1226 It was decided that it is more important to keep compatibility with
1227 ElementTree_ to simplify code migration between the libraries. The main
1228 difference compared to XPath is the ``{namespace}tagname`` notation used in
1229 ``findall()``, which is not valid XPath.
1230
1231 ElementTree and lxml.etree use the same implementation, which assures 100%
1232 compatibility. Note that ``findall()`` is `so fast`_ in lxml that a native
1233 implementation would not bring any performance benefits.
1234
1235 .. _`so fast`: performance.html#tree-traversal
1236
1237
1238 How can I find out which namespace prefixes are used in a document?
1239 -------------------------------------------------------------------
1240
1241 You can traverse the document (``root.iter()``) and collect the prefix
1242 attributes from all Elements into a set. However, it is unlikely that you
1243 really want to do that. You do not need these prefixes, honestly. You only
1244 need the namespace URIs. All namespace comparisons use these, so feel free to
1245 make up your own prefixes when you use XPath expressions or extension
1246 functions.
1247
1248 The only place where you might consider specifying prefixes is the
1249 serialization of Elements that were created through the API. Here, you can
1250 specify a prefix mapping through the ``nsmap`` argument when creating the root
1251 Element. Its children will then inherit this prefix for serialization.
1252
1253
1254 How can I specify a default namespace for XPath expressions?
1255 ------------------------------------------------------------
1256
1257 You can't. In XPath 1.0, there is no such thing as a default namespace. Just
1258 use an arbitrary prefix and let the namespace dictionary of the XPath evaluators
1259 map it to your namespace. See also the question above.
1260
1261
1262 How can I modify the tree during iteration?
1263 -------------------------------------------
1264
1265 lxml's iterators need to hold on to an element in the tree in order to remember
1266 their current position. Therefore, tree modifications between two calls into the
1267 iterator can lead to surprising results if such an element is deleted or moved
1268 around, for example.
1269
1270 If your code risks modifying elements that the iterator might still need, and
1271 you know that the number of elements returned by the iterator is small, then just
1272 read them all into a list (or use ``.findall()``), and iterate over that list.
1273
1274 If the number of elements can be larger and you really want to process the tree
1275 incrementally, you can often use a read-ahead generator to make the iterator
1276 advance beyond the critical point before touching the tree structure.
1277
1278 For example:
1279
1280 .. sourcecode:: python
1281
1282 from itertools import islice
1283 from collections import deque
1284
1285 def readahead(iterator, count=1):
1286 iterator = iter(iterator) # allow iterables as well
1287 elements = deque(islice(iterator, 0, count))
1288 for element in iterator:
1289 elements.append(element)
1290 yield elements.popleft()
1291 yield from elements
1292
1293 for element in readahead(root.iterfind("path/to/children")):
1294 element.getparent().remove(element)