| 1 |
======================================= |
| 2 |
ElementTree compatibility of lxml.etree |
| 3 |
======================================= |
| 4 |
|
| 5 |
A lot of care has been taken to ensure compatibility between etree and |
| 6 |
ElementTree. Nonetheless, some differences and incompatibilities exist: |
| 7 |
|
| 8 |
* Importing etree is obviously different; etree uses a lower-case |
| 9 |
package name, while ElementTree uses a combination of upper-case and |
| 10 |
lower-case in imports: |
| 11 |
|
| 12 |
.. sourcecode:: python |
| 13 |
|
| 14 |
# etree |
| 15 |
from lxml.etree import Element |
| 16 |
|
| 17 |
# ElementTree |
| 18 |
from elementtree.ElementTree import Element |
| 19 |
|
| 20 |
# ElementTree in the Python 2.5 standard library |
| 21 |
from xml.etree.ElementTree import Element |
| 22 |
|
| 23 |
When switching over code from ElementTree to lxml.etree, and you're using |
| 24 |
the package name prefix 'ElementTree', you can do the following: |
| 25 |
|
| 26 |
.. sourcecode:: python |
| 27 |
|
| 28 |
# instead of |
| 29 |
from elementtree import ElementTree |
| 30 |
# use |
| 31 |
from lxml import etree as ElementTree |
| 32 |
|
| 33 |
* lxml.etree offers a lot more functionality, such as XPath, XSLT, Relax NG, |
| 34 |
and XML Schema support, which (c)ElementTree does not offer. |
| 35 |
|
| 36 |
* etree has a different idea about Python unicode strings than ElementTree. |
| 37 |
In most parts of the API, ElementTree uses plain strings and unicode strings |
| 38 |
as what they are. This includes Element.text, Element.tail and many other |
| 39 |
places. However, the ElementTree parsers assume by default that any string |
| 40 |
(`str` or `unicode`) contains ASCII data. They raise an exception if |
| 41 |
strings do not match the expected encoding. |
| 42 |
|
| 43 |
etree has the same idea about plain strings (`str`) as ElementTree. For |
| 44 |
unicode strings, however, etree assumes throughout the API that they are |
| 45 |
Python unicode encoded strings rather than byte data. This includes the |
| 46 |
parsers. It is therefore perfectly correct to pass XML unicode data into |
| 47 |
the etree parsers in form of Python unicode strings. It is an error, on the |
| 48 |
other hand, if unicode strings specify an encoding in their XML declaration, |
| 49 |
as this conflicts with the characteristic encoding of Python unicode |
| 50 |
strings. |
| 51 |
|
| 52 |
* ElementTree allows you to place an Element in two different trees at the |
| 53 |
same time. Thus, this: |
| 54 |
|
| 55 |
.. sourcecode:: python |
| 56 |
|
| 57 |
a = Element('a') |
| 58 |
b = SubElement(a, 'b') |
| 59 |
c = Element('c') |
| 60 |
c.append(b) |
| 61 |
|
| 62 |
will result in the following tree a: |
| 63 |
|
| 64 |
.. sourcecode:: xml |
| 65 |
|
| 66 |
<a><b /></a> |
| 67 |
|
| 68 |
and the following tree c: |
| 69 |
|
| 70 |
.. sourcecode:: xml |
| 71 |
|
| 72 |
<c><b /></c> |
| 73 |
|
| 74 |
In lxml, this behavior is different, because lxml is built on top of a tree |
| 75 |
that maintains parent relationships for elements (like W3C DOM). This means |
| 76 |
an element can only exist in a single tree at the same time. Adding an |
| 77 |
element in some tree to another tree will cause this element to be moved. |
| 78 |
|
| 79 |
So, for tree a we will get: |
| 80 |
|
| 81 |
.. sourcecode:: xml |
| 82 |
|
| 83 |
<a></a> |
| 84 |
|
| 85 |
and for tree c we will get: |
| 86 |
|
| 87 |
.. sourcecode:: xml |
| 88 |
|
| 89 |
<c><b/></c> |
| 90 |
|
| 91 |
Unfortunately this is a rather fundamental difference in behavior, which is |
| 92 |
hard to change. It won't affect some applications, but if you want to port |
| 93 |
code you must unfortunately make sure that it doesn't affect yours. |
| 94 |
|
| 95 |
* etree allows navigation to the parent of a node by the ``getparent()`` |
| 96 |
method and to the siblings by calling ``getnext()`` and ``getprevious()``. |
| 97 |
This is not possible in ElementTree as the underlying tree model does not |
| 98 |
have this information. |
| 99 |
|
| 100 |
* When trying to set a subelement using __setitem__ that is in fact not an |
| 101 |
Element but some other object, etree raises a TypeError, and ElementTree |
| 102 |
raises an AssertionError. This also applies to some other places of the |
| 103 |
API. In general, etree tries to avoid AssertionErrors in favour of being |
| 104 |
more specific about the reason for the exception. |
| 105 |
|
| 106 |
* When parsing fails in ``iterparse()``, ElementTree up to version |
| 107 |
1.2.x raises a low-level ``ExpatError`` instead of a ``SyntaxError`` |
| 108 |
as the other parsers. Both lxml and ElementTree 1.3 raise a |
| 109 |
``ParseError`` for parser errors. |
| 110 |
|
| 111 |
* The ``iterparse()`` function in lxml is implemented based on the libxml2 |
| 112 |
parser and tree generator. This means that modifications of the document |
| 113 |
root or the ancestors of the current element during parsing can irritate the |
| 114 |
parser and even segfault. While this is not a problem in the Python object |
| 115 |
structure used by ElementTree, the C tree underlying lxml suffers from it. |
| 116 |
The golden rule for ``iterparse()`` on lxml therefore is: do not touch |
| 117 |
anything that will have to be touched again by the parser later on. See the |
| 118 |
lxml parser documentation on this. |
| 119 |
|
| 120 |
* ElementTree ignores comments and processing instructions when parsing XML, |
| 121 |
while etree will read them in and treat them as Comment or |
| 122 |
ProcessingInstruction elements respectively. This is especially visible |
| 123 |
where comments are found inside text content, which is then split by the |
| 124 |
Comment element. |
| 125 |
|
| 126 |
You can disable this behaviour by passing the boolean ``remove_comments`` |
| 127 |
and/or ``remove_pis`` keyword arguments to the parser you use. For |
| 128 |
convenience and to support portable code, you can also use the |
| 129 |
``etree.ETCompatXMLParser`` instead of the default ``etree.XMLParser``. It |
| 130 |
tries to provide a default setup that is as close to the ElementTree parser |
| 131 |
as possible. |
| 132 |
|
| 133 |
* The ``TreeBuilder`` class of ``lxml.etree`` uses a different |
| 134 |
signature for the ``start()`` method. It accepts an additional |
| 135 |
argument ``nsmap`` to propagate the namespace declarations of an |
| 136 |
element in addition to its own namespace. To assure compatibility |
| 137 |
with ElementTree (which does not support this argument), lxml checks |
| 138 |
if the method accepts 3 arguments before calling it, and otherwise |
| 139 |
drops the namespace mapping. This should work with most existing |
| 140 |
ElementTree code, although there may still be conflicting cases. |
| 141 |
|
| 142 |
* ElementTree 1.2 has a bug when serializing an empty Comment (no text |
| 143 |
argument given) to XML, etree serializes this successfully. |
| 144 |
|
| 145 |
* ElementTree adds whitespace around comments on serialization, lxml does |
| 146 |
not. This means that a comment text "text" that ElementTree serializes as |
| 147 |
"<!-- text -->" will become "<!--text-->" in lxml. |
| 148 |
|
| 149 |
* When the string ``'*'`` is used as tag filter in the ``Element.iter()`` and |
| 150 |
``.find*()`` methods, ElementTree returns all elements in the tree, including |
| 151 |
comments and processing instructions. lxml.etree only returns real Elements, |
| 152 |
i.e. tree nodes that have a string tag name. Without a filter, both libraries |
| 153 |
iterate over all nodes. |
| 154 |
|
| 155 |
Note that currently only lxml.etree supports passing the ``Element`` factory |
| 156 |
function as filter to select only Elements. Both libraries support passing |
| 157 |
the ``Comment`` and ``ProcessingInstruction`` factories to select the |
| 158 |
respective tree nodes. |
| 159 |
|
| 160 |
* ElementTree merges the target of a processing instruction into ``PI.text``, |
| 161 |
while lxml.etree puts it into the ``.target`` property and leaves it out of |
| 162 |
the ``.text`` property. The ``pi.text`` in ElementTree therefore |
| 163 |
corresponds to ``pi.target + " " + pi.text`` in lxml.etree. |
| 164 |
|
| 165 |
* Because etree is built on top of libxml2, which is namespace prefix aware, |
| 166 |
etree preserves namespaces declarations and prefixes while ElementTree tends |
| 167 |
to come up with its own prefixes (ns0, ns1, etc). When no namespace prefix |
| 168 |
is given, however, etree creates ElementTree style prefixes as well. |
| 169 |
|
| 170 |
* etree has a 'prefix' attribute (read-only) on elements giving the Element's |
| 171 |
prefix, if this is known, and None otherwise (in case of no namespace at |
| 172 |
all, or default namespace). |
| 173 |
|
| 174 |
* etree further allows passing an 'nsmap' dictionary to the Element and |
| 175 |
SubElement element factories to explicitly map namespace prefixes to |
| 176 |
namespace URIs. These will be translated into namespace declarations on |
| 177 |
that element. This means that in the probably rare case that you need to |
| 178 |
construct an attribute called 'nsmap', you need to be aware that unlike in |
| 179 |
ElementTree, you cannot pass it as a keyword argument to the Element and |
| 180 |
SubElement factories directly. |
| 181 |
|
| 182 |
* ElementTree allows QName objects as attribute values and resolves their |
| 183 |
prefix on serialisation (e.g. an attribute value ``QName("{myns}myname")`` |
| 184 |
becomes "p:myname" if "p" is the namespace prefix of "myns"). lxml.etree |
| 185 |
also allows you to set attribute values from QName instances (and also .text |
| 186 |
values), but it resolves their prefix immediately and stores the plain text |
| 187 |
value. So, if prefixes are modified later on, e.g. by moving a subtree to a |
| 188 |
different tree (which reassigns the prefix mappings), the text values will |
| 189 |
not be updated and you might end up with an undefined prefix. |
| 190 |
|
| 191 |
* etree elements can be copied using ``copy.deepcopy()`` and ``copy.copy()``, |
| 192 |
just like ElementTree's. However, ``copy.copy()`` does *not* create a |
| 193 |
shallow copy where elements are shared between trees, as this makes no sense |
| 194 |
in the context of libxml2 trees. Note that lxml can deep-copy trees |
| 195 |
considerably faster than ElementTree, so a deep copy might still be fast |
| 196 |
enough to replace a shallow copy in your case. |