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