FAQ.txt 50 KB

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