| 1 |
======================= |
| 2 |
The lxml.etree Tutorial |
| 3 |
======================= |
| 4 |
|
| 5 |
.. meta:: |
| 6 |
:description: The lxml tutorial on XML processing with Python |
| 7 |
:keywords: XML processing with Python, lxml, lxml.etree, tutorial, ElementTree, Python, XML, HTML |
| 8 |
|
| 9 |
:Author: |
| 10 |
Stefan Behnel |
| 11 |
|
| 12 |
This is a tutorial on XML processing with ``lxml.etree``. It briefly |
| 13 |
overviews the main concepts of the `ElementTree API`_, and some simple |
| 14 |
enhancements that make your life as a programmer easier. |
| 15 |
|
| 16 |
For a complete reference of the API, see the `generated API |
| 17 |
documentation`_. |
| 18 |
|
| 19 |
.. _`ElementTree API`: https://docs.python.org/3/library/xml.etree.elementtree.html |
| 20 |
.. _`generated API documentation`: api/index.html |
| 21 |
|
| 22 |
.. contents:: |
| 23 |
.. |
| 24 |
1 The Element class |
| 25 |
1.1 Elements are lists |
| 26 |
1.2 Elements carry attributes |
| 27 |
1.3 Elements contain text |
| 28 |
1.4 Using XPath to find text |
| 29 |
1.5 Tree iteration |
| 30 |
1.6 Serialisation |
| 31 |
2 The ElementTree class |
| 32 |
3 Parsing from strings and files |
| 33 |
3.1 The fromstring() function |
| 34 |
3.2 The XML() function |
| 35 |
3.3 The parse() function |
| 36 |
3.4 Parser objects |
| 37 |
3.5 Incremental parsing |
| 38 |
3.6 Event-driven parsing |
| 39 |
4 Namespaces |
| 40 |
5 The E-factory |
| 41 |
6 ElementPath |
| 42 |
|
| 43 |
|
| 44 |
A common way to import ``lxml.etree`` is as follows: |
| 45 |
|
| 46 |
.. sourcecode:: pycon |
| 47 |
|
| 48 |
>>> from lxml import etree |
| 49 |
|
| 50 |
If your code only uses the ElementTree API and does not rely on any |
| 51 |
functionality that is specific to ``lxml.etree``, you can also use the following |
| 52 |
import chain as a fall-back to ElementTree in the Python standard library: |
| 53 |
|
| 54 |
.. sourcecode:: python |
| 55 |
|
| 56 |
try: |
| 57 |
from lxml import etree |
| 58 |
print("running with lxml.etree") |
| 59 |
except ImportError: |
| 60 |
import xml.etree.ElementTree as etree |
| 61 |
print("running with Python's xml.etree.ElementTree") |
| 62 |
|
| 63 |
To aid in writing portable code, this tutorial makes it clear in the examples |
| 64 |
which part of the presented API is an extension of ``lxml.etree`` over the |
| 65 |
original `ElementTree API`_. |
| 66 |
|
| 67 |
|
| 68 |
The Element class |
| 69 |
================= |
| 70 |
|
| 71 |
An ``Element`` is the main container object for the ElementTree API. Most of |
| 72 |
the XML tree functionality is accessed through this class. Elements are |
| 73 |
easily created through the ``Element`` factory: |
| 74 |
|
| 75 |
.. sourcecode:: pycon |
| 76 |
|
| 77 |
>>> root = etree.Element("root") |
| 78 |
|
| 79 |
The XML tag name of elements is accessed through the ``tag`` property: |
| 80 |
|
| 81 |
.. sourcecode:: pycon |
| 82 |
|
| 83 |
>>> print(root.tag) |
| 84 |
root |
| 85 |
|
| 86 |
Elements are organised in an XML tree structure. To create child elements and |
| 87 |
add them to a parent element, you can use the ``append()`` method: |
| 88 |
|
| 89 |
.. sourcecode:: pycon |
| 90 |
|
| 91 |
>>> root.append( etree.Element("child1") ) |
| 92 |
|
| 93 |
However, this is so common that there is a shorter and much more efficient way |
| 94 |
to do this: the ``SubElement`` factory. It accepts the same arguments as the |
| 95 |
``Element`` factory, but additionally requires the parent as first argument: |
| 96 |
|
| 97 |
.. sourcecode:: pycon |
| 98 |
|
| 99 |
>>> child2 = etree.SubElement(root, "child2") |
| 100 |
>>> child3 = etree.SubElement(root, "child3") |
| 101 |
|
| 102 |
To see that this is really XML, you can serialise the tree you have created: |
| 103 |
|
| 104 |
.. sourcecode:: pycon |
| 105 |
|
| 106 |
>>> etree.tostring(root) |
| 107 |
b'<root><child1/><child2/><child3/></root>' |
| 108 |
|
| 109 |
We'll create a little helper function to pretty-print the XML for us: |
| 110 |
|
| 111 |
>>> def prettyprint(element, **kwargs): |
| 112 |
... xml = etree.tostring(element, pretty_print=True, **kwargs) |
| 113 |
... print(xml.decode(), end='') |
| 114 |
|
| 115 |
>>> prettyprint(root) |
| 116 |
<root> |
| 117 |
<child1/> |
| 118 |
<child2/> |
| 119 |
<child3/> |
| 120 |
</root> |
| 121 |
|
| 122 |
|
| 123 |
Elements are lists |
| 124 |
------------------ |
| 125 |
|
| 126 |
To make the access to these subelements easy and straightforward, |
| 127 |
elements mimic the behaviour of normal Python lists as closely as |
| 128 |
possible: |
| 129 |
|
| 130 |
.. sourcecode:: pycon |
| 131 |
|
| 132 |
>>> child = root[0] |
| 133 |
>>> print(child.tag) |
| 134 |
child1 |
| 135 |
|
| 136 |
>>> print(len(root)) |
| 137 |
3 |
| 138 |
|
| 139 |
>>> root.index(root[1]) # lxml.etree only! |
| 140 |
1 |
| 141 |
|
| 142 |
>>> children = list(root) |
| 143 |
|
| 144 |
>>> for child in root: |
| 145 |
... print(child.tag) |
| 146 |
child1 |
| 147 |
child2 |
| 148 |
child3 |
| 149 |
|
| 150 |
>>> root.insert(0, etree.Element("child0")) |
| 151 |
>>> start = root[:1] |
| 152 |
>>> end = root[-1:] |
| 153 |
|
| 154 |
>>> print(start[0].tag) |
| 155 |
child0 |
| 156 |
>>> print(end[0].tag) |
| 157 |
child3 |
| 158 |
|
| 159 |
Prior to ElementTree 1.3 and lxml 2.0, you could also check the truth value of |
| 160 |
an Element to see if it has children, i.e. if the list of children is empty: |
| 161 |
|
| 162 |
.. sourcecode:: python |
| 163 |
|
| 164 |
if root: # this no longer works! |
| 165 |
print("The root element has children") |
| 166 |
|
| 167 |
This is no longer supported as people tend to expect that a "something" |
| 168 |
evaluates to True and expect Elements to be "something", whether they have |
| 169 |
children or not. So, many users find it surprising that any Element |
| 170 |
would evaluate to False in an if-statement like the above. Instead, |
| 171 |
use ``len(element)``, which is both more explicit and less error prone. |
| 172 |
|
| 173 |
.. sourcecode:: pycon |
| 174 |
|
| 175 |
>>> print(etree.iselement(root)) # test if it's some kind of Element |
| 176 |
True |
| 177 |
>>> if len(root): # test if it has children |
| 178 |
... print("The root element has children") |
| 179 |
The root element has children |
| 180 |
|
| 181 |
There is another important case where the behaviour of Elements in lxml |
| 182 |
(in 2.0 and later) deviates from that of lists and from that of the |
| 183 |
original ElementTree (prior to version 1.3 or Python 2.7/3.2): |
| 184 |
|
| 185 |
.. sourcecode:: pycon |
| 186 |
|
| 187 |
>>> for child in root: |
| 188 |
... print(child.tag) |
| 189 |
child0 |
| 190 |
child1 |
| 191 |
child2 |
| 192 |
child3 |
| 193 |
>>> root[0] = root[-1] # this moves the element in lxml.etree! |
| 194 |
>>> for child in root: |
| 195 |
... print(child.tag) |
| 196 |
child3 |
| 197 |
child1 |
| 198 |
child2 |
| 199 |
|
| 200 |
In this example, the last element is *moved* to a different position, |
| 201 |
instead of being copied, i.e. it is automatically removed from its |
| 202 |
previous position when it is put in a different place. In lists, |
| 203 |
objects can appear in multiple positions at the same time, and the |
| 204 |
above assignment would just copy the item reference into the first |
| 205 |
position, so that both contain the exact same item: |
| 206 |
|
| 207 |
.. sourcecode:: pycon |
| 208 |
|
| 209 |
>>> l = [0, 1, 2, 3] |
| 210 |
>>> l[0] = l[-1] |
| 211 |
>>> l |
| 212 |
[3, 1, 2, 3] |
| 213 |
|
| 214 |
Note that in the original ElementTree, a single Element object can sit |
| 215 |
in any number of places in any number of trees, which allows for the same |
| 216 |
copy operation as with lists. The obvious drawback is that modifications |
| 217 |
to such an Element will apply to all places where it appears in a tree, |
| 218 |
which may or may not be intended. |
| 219 |
|
| 220 |
The upside of this difference is that an Element in ``lxml.etree`` always |
| 221 |
has exactly one parent, which can be queried through the ``getparent()`` |
| 222 |
method. This is not supported in the original ElementTree. |
| 223 |
|
| 224 |
.. sourcecode:: pycon |
| 225 |
|
| 226 |
>>> root is root[0].getparent() # lxml.etree only! |
| 227 |
True |
| 228 |
|
| 229 |
If you want to *copy* an element to a different position in ``lxml.etree``, |
| 230 |
consider creating an independent *deep copy* using the ``copy`` module |
| 231 |
from Python's standard library: |
| 232 |
|
| 233 |
.. sourcecode:: pycon |
| 234 |
|
| 235 |
>>> from copy import deepcopy |
| 236 |
|
| 237 |
>>> element = etree.Element("neu") |
| 238 |
>>> element.append( deepcopy(root[1]) ) |
| 239 |
|
| 240 |
>>> print(element[0].tag) |
| 241 |
child1 |
| 242 |
>>> print([ c.tag for c in root ]) |
| 243 |
['child3', 'child1', 'child2'] |
| 244 |
|
| 245 |
The siblings (or neighbours) of an element are accessed as next and previous |
| 246 |
elements: |
| 247 |
|
| 248 |
.. sourcecode:: pycon |
| 249 |
|
| 250 |
>>> root[0] is root[1].getprevious() # lxml.etree only! |
| 251 |
True |
| 252 |
>>> root[1] is root[0].getnext() # lxml.etree only! |
| 253 |
True |
| 254 |
|
| 255 |
|
| 256 |
Elements carry attributes as a dict |
| 257 |
----------------------------------- |
| 258 |
|
| 259 |
XML elements support attributes. You can create them directly in the Element |
| 260 |
factory: |
| 261 |
|
| 262 |
.. sourcecode:: pycon |
| 263 |
|
| 264 |
>>> root = etree.Element("root", interesting="totally") |
| 265 |
>>> etree.tostring(root) |
| 266 |
b'<root interesting="totally"/>' |
| 267 |
|
| 268 |
Attributes are just unordered name-value pairs, so a very convenient way |
| 269 |
of dealing with them is through the dictionary-like interface of Elements: |
| 270 |
|
| 271 |
.. sourcecode:: pycon |
| 272 |
|
| 273 |
>>> print(root.get("interesting")) |
| 274 |
totally |
| 275 |
|
| 276 |
>>> print(root.get("hello")) |
| 277 |
None |
| 278 |
>>> root.set("hello", "Huhu") |
| 279 |
>>> print(root.get("hello")) |
| 280 |
Huhu |
| 281 |
|
| 282 |
>>> etree.tostring(root) |
| 283 |
b'<root interesting="totally" hello="Huhu"/>' |
| 284 |
|
| 285 |
>>> sorted(root.keys()) |
| 286 |
['hello', 'interesting'] |
| 287 |
|
| 288 |
>>> for name, value in sorted(root.items()): |
| 289 |
... print('%s = %r' % (name, value)) |
| 290 |
hello = 'Huhu' |
| 291 |
interesting = 'totally' |
| 292 |
|
| 293 |
For the cases where you want to do item lookup or have other reasons for |
| 294 |
getting a 'real' dictionary-like object, e.g. for passing it around, |
| 295 |
you can use the ``attrib`` property: |
| 296 |
|
| 297 |
.. sourcecode:: pycon |
| 298 |
|
| 299 |
>>> attributes = root.attrib |
| 300 |
|
| 301 |
>>> print(attributes["interesting"]) |
| 302 |
totally |
| 303 |
>>> print(attributes.get("no-such-attribute")) |
| 304 |
None |
| 305 |
|
| 306 |
>>> attributes["hello"] = "Guten Tag" |
| 307 |
>>> print(attributes["hello"]) |
| 308 |
Guten Tag |
| 309 |
>>> print(root.get("hello")) |
| 310 |
Guten Tag |
| 311 |
|
| 312 |
Note that ``attrib`` is a dict-like object backed by the Element itself. |
| 313 |
This means that any changes to the Element are reflected in ``attrib`` |
| 314 |
and vice versa. It also means that the XML tree stays alive in memory |
| 315 |
as long as the ``attrib`` of one of its Elements is in use. To get an |
| 316 |
independent snapshot of the attributes that does not depend on the XML |
| 317 |
tree, copy it into a dict: |
| 318 |
|
| 319 |
.. sourcecode:: pycon |
| 320 |
|
| 321 |
>>> d = dict(root.attrib) |
| 322 |
>>> sorted(d.items()) |
| 323 |
[('hello', 'Guten Tag'), ('interesting', 'totally')] |
| 324 |
|
| 325 |
|
| 326 |
Elements contain text |
| 327 |
--------------------- |
| 328 |
|
| 329 |
Elements can contain text: |
| 330 |
|
| 331 |
.. sourcecode:: pycon |
| 332 |
|
| 333 |
>>> root = etree.Element("root") |
| 334 |
>>> root.text = "TEXT" |
| 335 |
|
| 336 |
>>> print(root.text) |
| 337 |
TEXT |
| 338 |
|
| 339 |
>>> etree.tostring(root) |
| 340 |
b'<root>TEXT</root>' |
| 341 |
|
| 342 |
In many XML documents (*data-centric* documents), this is the only place where |
| 343 |
text can be found. It is encapsulated by a leaf tag at the very bottom of the |
| 344 |
tree hierarchy. |
| 345 |
|
| 346 |
However, if XML is used for tagged text documents such as (X)HTML, text can |
| 347 |
also appear between different elements, right in the middle of the tree: |
| 348 |
|
| 349 |
.. sourcecode:: html |
| 350 |
|
| 351 |
<html><body>Hello<br/>World</body></html> |
| 352 |
|
| 353 |
Here, the ``<br/>`` tag is surrounded by text. This is often referred to as |
| 354 |
*document-style* or *mixed-content* XML. Elements support this through their |
| 355 |
``tail`` property. It contains the text that directly follows the element, up |
| 356 |
to the next element in the XML tree: |
| 357 |
|
| 358 |
.. sourcecode:: pycon |
| 359 |
|
| 360 |
>>> html = etree.Element("html") |
| 361 |
>>> body = etree.SubElement(html, "body") |
| 362 |
>>> body.text = "TEXT" |
| 363 |
|
| 364 |
>>> etree.tostring(html) |
| 365 |
b'<html><body>TEXT</body></html>' |
| 366 |
|
| 367 |
>>> br = etree.SubElement(body, "br") |
| 368 |
>>> etree.tostring(html) |
| 369 |
b'<html><body>TEXT<br/></body></html>' |
| 370 |
|
| 371 |
>>> br.tail = "TAIL" |
| 372 |
>>> etree.tostring(html) |
| 373 |
b'<html><body>TEXT<br/>TAIL</body></html>' |
| 374 |
|
| 375 |
The two properties ``.text`` and ``.tail`` are enough to represent any |
| 376 |
text content in an XML document. This way, the ElementTree API does |
| 377 |
not require any `special text nodes`_ in addition to the Element |
| 378 |
class, that tend to get in the way fairly often (as you might know |
| 379 |
from classic DOM_ APIs). |
| 380 |
|
| 381 |
However, there are cases where the tail text also gets in the way. |
| 382 |
For example, when you serialise an Element from within the tree, you |
| 383 |
do not always want its tail text in the result (although you would |
| 384 |
still want the tail text of its children). For this purpose, the |
| 385 |
``tostring()`` function accepts the keyword argument ``with_tail``: |
| 386 |
|
| 387 |
.. sourcecode:: pycon |
| 388 |
|
| 389 |
>>> etree.tostring(br) |
| 390 |
b'<br/>TAIL' |
| 391 |
>>> etree.tostring(br, with_tail=False) # lxml.etree only! |
| 392 |
b'<br/>' |
| 393 |
|
| 394 |
.. _`special text nodes`: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772 |
| 395 |
.. _DOM: http://www.w3.org/TR/DOM-Level-3-Core/core.html |
| 396 |
|
| 397 |
If you want to read *only* the text, i.e. without any intermediate |
| 398 |
tags, you have to recursively concatenate all ``text`` and ``tail`` |
| 399 |
attributes in the correct order. Again, the ``tostring()`` function |
| 400 |
comes to the rescue, this time using the ``method`` keyword: |
| 401 |
|
| 402 |
.. sourcecode:: pycon |
| 403 |
|
| 404 |
>>> etree.tostring(html, method="text") |
| 405 |
b'TEXTTAIL' |
| 406 |
|
| 407 |
|
| 408 |
Using XPath to find text |
| 409 |
------------------------ |
| 410 |
|
| 411 |
.. _XPath: xpathxslt.html#xpath |
| 412 |
|
| 413 |
Another way to extract the text content of a tree is XPath_, which |
| 414 |
also allows you to extract the separate text chunks into a list: |
| 415 |
|
| 416 |
.. sourcecode:: pycon |
| 417 |
|
| 418 |
>>> print(html.xpath("string()")) # lxml.etree only! |
| 419 |
TEXTTAIL |
| 420 |
>>> print(html.xpath("//text()")) # lxml.etree only! |
| 421 |
['TEXT', 'TAIL'] |
| 422 |
|
| 423 |
If you want to use this more often, you can wrap it in a function: |
| 424 |
|
| 425 |
.. sourcecode:: pycon |
| 426 |
|
| 427 |
>>> build_text_list = etree.XPath("//text()") # lxml.etree only! |
| 428 |
>>> print(build_text_list(html)) |
| 429 |
['TEXT', 'TAIL'] |
| 430 |
|
| 431 |
Note that a string result returned by XPath is a special 'smart' |
| 432 |
object that knows about its origins. You can ask it where it came |
| 433 |
from through its ``getparent()`` method, just as you would with |
| 434 |
Elements: |
| 435 |
|
| 436 |
.. sourcecode:: pycon |
| 437 |
|
| 438 |
>>> texts = build_text_list(html) |
| 439 |
>>> print(texts[0]) |
| 440 |
TEXT |
| 441 |
>>> parent = texts[0].getparent() |
| 442 |
>>> print(parent.tag) |
| 443 |
body |
| 444 |
|
| 445 |
>>> print(texts[1]) |
| 446 |
TAIL |
| 447 |
>>> print(texts[1].getparent().tag) |
| 448 |
br |
| 449 |
|
| 450 |
You can also find out if it's normal text content or tail text: |
| 451 |
|
| 452 |
.. sourcecode:: pycon |
| 453 |
|
| 454 |
>>> print(texts[0].is_text) |
| 455 |
True |
| 456 |
>>> print(texts[1].is_text) |
| 457 |
False |
| 458 |
>>> print(texts[1].is_tail) |
| 459 |
True |
| 460 |
|
| 461 |
While this works for the results of the ``text()`` function, lxml will |
| 462 |
not tell you the origin of a string value that was constructed by the |
| 463 |
XPath functions ``string()`` or ``concat()``: |
| 464 |
|
| 465 |
.. sourcecode:: pycon |
| 466 |
|
| 467 |
>>> stringify = etree.XPath("string()") |
| 468 |
>>> print(stringify(html)) |
| 469 |
TEXTTAIL |
| 470 |
>>> print(stringify(html).getparent()) |
| 471 |
None |
| 472 |
|
| 473 |
|
| 474 |
Tree iteration |
| 475 |
-------------- |
| 476 |
|
| 477 |
For problems like the above, where you want to recursively traverse the tree |
| 478 |
and do something with its elements, tree iteration is a very convenient |
| 479 |
solution. Elements provide a tree iterator for this purpose. It yields |
| 480 |
elements in *document order*, i.e. in the order their tags would appear if you |
| 481 |
serialised the tree to XML: |
| 482 |
|
| 483 |
.. sourcecode:: pycon |
| 484 |
|
| 485 |
>>> root = etree.Element("root") |
| 486 |
>>> etree.SubElement(root, "child").text = "Child 1" |
| 487 |
>>> etree.SubElement(root, "child").text = "Child 2" |
| 488 |
>>> etree.SubElement(root, "another").text = "Child 3" |
| 489 |
|
| 490 |
>>> prettyprint(root) |
| 491 |
<root> |
| 492 |
<child>Child 1</child> |
| 493 |
<child>Child 2</child> |
| 494 |
<another>Child 3</another> |
| 495 |
</root> |
| 496 |
|
| 497 |
>>> for element in root.iter(): |
| 498 |
... print(f"{element.tag} - {element.text}") |
| 499 |
root - None |
| 500 |
child - Child 1 |
| 501 |
child - Child 2 |
| 502 |
another - Child 3 |
| 503 |
|
| 504 |
If you know you are only interested in a single tag, you can pass its name to |
| 505 |
``iter()`` to have it filter for you. Starting with lxml 3.0, you can also |
| 506 |
pass more than one tag to intercept on multiple tags during iteration. |
| 507 |
|
| 508 |
.. sourcecode:: pycon |
| 509 |
|
| 510 |
>>> for element in root.iter("child"): |
| 511 |
... print(f"{element.tag} - {element.text}") |
| 512 |
child - Child 1 |
| 513 |
child - Child 2 |
| 514 |
|
| 515 |
>>> for element in root.iter("another", "child"): |
| 516 |
... print(f"{element.tag} - {element.text}") |
| 517 |
child - Child 1 |
| 518 |
child - Child 2 |
| 519 |
another - Child 3 |
| 520 |
|
| 521 |
By default, iteration yields all nodes in the tree, including |
| 522 |
ProcessingInstructions, Comments and Entity instances. If you want to |
| 523 |
make sure only Element objects are returned, you can pass the |
| 524 |
``Element`` factory as tag parameter: |
| 525 |
|
| 526 |
.. sourcecode:: pycon |
| 527 |
|
| 528 |
>>> root.append(etree.Entity("#234")) |
| 529 |
>>> root.append(etree.Comment("some comment")) |
| 530 |
|
| 531 |
>>> for element in root.iter(): |
| 532 |
... if isinstance(element.tag, str): |
| 533 |
... print(f"{element.tag} - {element.text}") |
| 534 |
... else: |
| 535 |
... print(f"SPECIAL: {element} - {element.text}") |
| 536 |
root - None |
| 537 |
child - Child 1 |
| 538 |
child - Child 2 |
| 539 |
another - Child 3 |
| 540 |
SPECIAL: ê - ê |
| 541 |
SPECIAL: <!--some comment--> - some comment |
| 542 |
|
| 543 |
>>> for element in root.iter(tag=etree.Element): |
| 544 |
... print(f"{element.tag} - {element.text}") |
| 545 |
root - None |
| 546 |
child - Child 1 |
| 547 |
child - Child 2 |
| 548 |
another - Child 3 |
| 549 |
|
| 550 |
>>> for element in root.iter(tag=etree.Entity): |
| 551 |
... print(element.text) |
| 552 |
ê |
| 553 |
|
| 554 |
Note that passing a wildcard ``"*"`` tag name will also yield all |
| 555 |
``Element`` nodes (and only elements). |
| 556 |
|
| 557 |
In ``lxml.etree``, elements provide `further iterators`_ for all directions in the |
| 558 |
tree: children, parents (or rather ancestors) and siblings. |
| 559 |
|
| 560 |
.. _`further iterators`: api.html#iteration |
| 561 |
|
| 562 |
|
| 563 |
Serialisation |
| 564 |
------------- |
| 565 |
|
| 566 |
Serialisation commonly uses the ``tostring()`` function that returns a |
| 567 |
string, or the ``ElementTree.write()`` method that writes to a file, a |
| 568 |
file-like object, or a URL (via FTP PUT or HTTP POST). Both calls accept |
| 569 |
the same keyword arguments like ``pretty_print`` for formatted output |
| 570 |
or ``encoding`` to select a specific output encoding other than plain |
| 571 |
ASCII: |
| 572 |
|
| 573 |
.. sourcecode:: pycon |
| 574 |
|
| 575 |
>>> root = etree.XML('<root><a><b/></a></root>') |
| 576 |
|
| 577 |
>>> etree.tostring(root) |
| 578 |
b'<root><a><b/></a></root>' |
| 579 |
|
| 580 |
>>> xml_string = etree.tostring(root, xml_declaration=True) |
| 581 |
>>> print(xml_string.decode(), end='') |
| 582 |
<?xml version='1.0' encoding='ASCII'?> |
| 583 |
<root><a><b/></a></root> |
| 584 |
|
| 585 |
>>> latin1_bytesstring = etree.tostring(root, encoding='iso8859-1') |
| 586 |
>>> print(latin1_bytesstring.decode('iso8859-1'), end='') |
| 587 |
<?xml version='1.0' encoding='iso8859-1'?> |
| 588 |
<root><a><b/></a></root> |
| 589 |
|
| 590 |
>>> print(etree.tostring(root, pretty_print=True).decode(), end='') |
| 591 |
<root> |
| 592 |
<a> |
| 593 |
<b/> |
| 594 |
</a> |
| 595 |
</root> |
| 596 |
|
| 597 |
Note that pretty printing appends a newline at the end. |
| 598 |
We therefore use the ``end=''`` option here to prevent the ``print()`` |
| 599 |
function from adding another line break. |
| 600 |
|
| 601 |
For more fine-grained control over the pretty-printing, you can add |
| 602 |
whitespace indentation to the tree before serialising it, using the |
| 603 |
``indent()`` function (added in lxml 4.5): |
| 604 |
|
| 605 |
.. sourcecode:: pycon |
| 606 |
|
| 607 |
>>> root = etree.XML('<root><a><b/>\n</a></root>') |
| 608 |
>>> print(etree.tostring(root).decode()) |
| 609 |
<root><a><b/> |
| 610 |
</a></root> |
| 611 |
|
| 612 |
>>> etree.indent(root) |
| 613 |
>>> print(etree.tostring(root).decode()) |
| 614 |
<root> |
| 615 |
<a> |
| 616 |
<b/> |
| 617 |
</a> |
| 618 |
</root> |
| 619 |
|
| 620 |
>>> root.text |
| 621 |
'\n ' |
| 622 |
>>> root[0].text |
| 623 |
'\n ' |
| 624 |
|
| 625 |
>>> etree.indent(root, space=" ") |
| 626 |
>>> print(etree.tostring(root).decode()) |
| 627 |
<root> |
| 628 |
<a> |
| 629 |
<b/> |
| 630 |
</a> |
| 631 |
</root> |
| 632 |
|
| 633 |
>>> etree.indent(root, space="\t") |
| 634 |
>>> etree.tostring(root) |
| 635 |
b'<root>\n\t<a>\n\t\t<b/>\n\t</a>\n</root>' |
| 636 |
|
| 637 |
In lxml 2.0 and later, as well as in ``xml.etree``, the serialisation |
| 638 |
functions can do more than XML serialisation. You can serialise to |
| 639 |
HTML or extract the text content by passing the ``method`` keyword: |
| 640 |
|
| 641 |
.. sourcecode:: pycon |
| 642 |
|
| 643 |
>>> root = etree.XML( |
| 644 |
... '<html><head/><body><p>Hello<br/>World</p></body></html>') |
| 645 |
|
| 646 |
>>> etree.tostring(root) # default: method = 'xml' |
| 647 |
b'<html><head/><body><p>Hello<br/>World</p></body></html>' |
| 648 |
|
| 649 |
>>> etree.tostring(root, method='xml') # same as above |
| 650 |
b'<html><head/><body><p>Hello<br/>World</p></body></html>' |
| 651 |
|
| 652 |
>>> etree.tostring(root, method='html') |
| 653 |
b'<html><head></head><body><p>Hello<br>World</p></body></html>' |
| 654 |
|
| 655 |
>>> prettyprint(root, method='html') |
| 656 |
<html> |
| 657 |
<head></head> |
| 658 |
<body><p>Hello<br>World</p></body> |
| 659 |
</html> |
| 660 |
|
| 661 |
>>> etree.tostring(root, method='text') |
| 662 |
b'HelloWorld' |
| 663 |
|
| 664 |
As for XML serialisation, the default encoding for plain text |
| 665 |
serialisation is ASCII: |
| 666 |
|
| 667 |
.. sourcecode:: pycon |
| 668 |
|
| 669 |
>>> br = next(root.iter('br')) # get first result of iteration |
| 670 |
>>> br.tail = 'Wörld' |
| 671 |
|
| 672 |
>>> etree.tostring(root, method='text') # doctest: +ELLIPSIS |
| 673 |
Traceback (most recent call last): |
| 674 |
... |
| 675 |
UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' ... |
| 676 |
|
| 677 |
>>> etree.tostring(root, method='text', encoding="UTF-8") |
| 678 |
b'HelloW\xc3\xb6rld' |
| 679 |
|
| 680 |
Here, serialising to a Python text string instead of a byte string |
| 681 |
might become handy. Just pass the name ``'unicode'`` as encoding: |
| 682 |
|
| 683 |
.. sourcecode:: pycon |
| 684 |
|
| 685 |
>>> etree.tostring(root, encoding='unicode', method='text') |
| 686 |
'HelloWörld' |
| 687 |
>>> etree.tostring(root, encoding='unicode') |
| 688 |
'<html><head/><body><p>Hello<br/>Wörld</p></body></html>' |
| 689 |
|
| 690 |
`The W3C has a good article about the Unicode character set and character encodings |
| 691 |
<http://www.w3.org/International/tutorials/tutorial-char-enc/>`_. |
| 692 |
|
| 693 |
|
| 694 |
The ElementTree class |
| 695 |
===================== |
| 696 |
|
| 697 |
An ``ElementTree`` is mainly a document wrapper around a tree with a |
| 698 |
root node. It provides a couple of methods for serialisation and |
| 699 |
general document handling. |
| 700 |
|
| 701 |
.. sourcecode:: pycon |
| 702 |
|
| 703 |
>>> root = etree.XML('''\ |
| 704 |
... <?xml version="1.0"?> |
| 705 |
... <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "parsnips"> ]> |
| 706 |
... <root> |
| 707 |
... <a>&tasty;</a> |
| 708 |
... </root> |
| 709 |
... ''') |
| 710 |
|
| 711 |
>>> tree = etree.ElementTree(root) |
| 712 |
>>> print(tree.docinfo.xml_version) |
| 713 |
1.0 |
| 714 |
>>> print(tree.docinfo.doctype) |
| 715 |
<!DOCTYPE root SYSTEM "test"> |
| 716 |
|
| 717 |
>>> tree.docinfo.public_id = '-//W3C//DTD XHTML 1.0 Transitional//EN' |
| 718 |
>>> tree.docinfo.system_url = 'file://local.dtd' |
| 719 |
>>> print(tree.docinfo.doctype) |
| 720 |
<!DOCTYPE root PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "file://local.dtd"> |
| 721 |
|
| 722 |
An ``ElementTree`` is also what you get back when you call the |
| 723 |
``parse()`` function to parse files or file-like objects (see the |
| 724 |
parsing section below). |
| 725 |
|
| 726 |
One of the important differences is that the ``ElementTree`` class |
| 727 |
serialises as a complete document, as opposed to a single ``Element``. |
| 728 |
This includes top-level processing instructions and comments, as well |
| 729 |
as a DOCTYPE and other DTD content in the document: |
| 730 |
|
| 731 |
.. sourcecode:: pycon |
| 732 |
|
| 733 |
>>> prettyprint(tree) # lxml 1.3.4 and later |
| 734 |
<!DOCTYPE root PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "file://local.dtd" [ |
| 735 |
<!ENTITY tasty "parsnips"> |
| 736 |
]> |
| 737 |
<root> |
| 738 |
<a>parsnips</a> |
| 739 |
</root> |
| 740 |
|
| 741 |
In the original xml.etree.ElementTree implementation and in lxml |
| 742 |
up to 1.3.3, the output looks the same as when serialising only |
| 743 |
the root Element: |
| 744 |
|
| 745 |
.. sourcecode:: pycon |
| 746 |
|
| 747 |
>>> prettyprint(tree.getroot()) |
| 748 |
<root> |
| 749 |
<a>parsnips</a> |
| 750 |
</root> |
| 751 |
|
| 752 |
This serialisation behaviour has changed in lxml 1.3.4. Before, |
| 753 |
the tree was serialised without DTD content, which made lxml |
| 754 |
lose DTD information in an input-output cycle. |
| 755 |
|
| 756 |
|
| 757 |
Parsing from strings and files |
| 758 |
============================== |
| 759 |
|
| 760 |
``lxml.etree`` supports parsing XML in a number of ways and from all |
| 761 |
important sources, namely strings, files, URLs (http/ftp) and |
| 762 |
file-like objects. The main parse functions are ``fromstring()`` and |
| 763 |
``parse()``, both called with the source as first argument. By |
| 764 |
default, they use the standard parser, but you can always pass a |
| 765 |
different parser as second argument. |
| 766 |
|
| 767 |
|
| 768 |
The fromstring() function |
| 769 |
------------------------- |
| 770 |
|
| 771 |
The ``fromstring()`` function is the easiest way to parse a string: |
| 772 |
|
| 773 |
.. sourcecode:: pycon |
| 774 |
|
| 775 |
>>> some_xml_data = "<root>data</root>" |
| 776 |
|
| 777 |
>>> root = etree.fromstring(some_xml_data) |
| 778 |
>>> print(root.tag) |
| 779 |
root |
| 780 |
>>> etree.tostring(root) |
| 781 |
b'<root>data</root>' |
| 782 |
|
| 783 |
|
| 784 |
The XML() function |
| 785 |
------------------ |
| 786 |
|
| 787 |
The ``XML()`` function behaves like the ``fromstring()`` function, but is |
| 788 |
commonly used to write XML literals right into the source: |
| 789 |
|
| 790 |
.. sourcecode:: pycon |
| 791 |
|
| 792 |
>>> root = etree.XML("<root>data</root>") |
| 793 |
>>> print(root.tag) |
| 794 |
root |
| 795 |
>>> etree.tostring(root) |
| 796 |
b'<root>data</root>' |
| 797 |
|
| 798 |
There is also a corresponding function ``HTML()`` for HTML literals. |
| 799 |
|
| 800 |
.. sourcecode:: pycon |
| 801 |
|
| 802 |
>>> root = etree.HTML("<p>data</p>") |
| 803 |
>>> etree.tostring(root) |
| 804 |
b'<html><body><p>data</p></body></html>' |
| 805 |
|
| 806 |
|
| 807 |
The parse() function |
| 808 |
-------------------- |
| 809 |
|
| 810 |
The ``parse()`` function is used to parse from files and file-like objects. |
| 811 |
|
| 812 |
As an example of such a file-like object, the following code uses the |
| 813 |
``BytesIO`` class for reading from a string instead of an external file. |
| 814 |
However, in real life, you would obviously avoid doing this and use the |
| 815 |
string parsing functions like ``fromstring()`` above. |
| 816 |
|
| 817 |
.. sourcecode:: pycon |
| 818 |
|
| 819 |
>>> from io import BytesIO |
| 820 |
>>> some_file_or_file_like_object = BytesIO(b"<root>data</root>") |
| 821 |
|
| 822 |
>>> tree = etree.parse(some_file_or_file_like_object) |
| 823 |
|
| 824 |
>>> etree.tostring(tree) |
| 825 |
b'<root>data</root>' |
| 826 |
|
| 827 |
Note that ``parse()`` returns an ElementTree object, not an Element object as |
| 828 |
the string parser functions: |
| 829 |
|
| 830 |
.. sourcecode:: pycon |
| 831 |
|
| 832 |
>>> root = tree.getroot() |
| 833 |
>>> print(root.tag) |
| 834 |
root |
| 835 |
>>> etree.tostring(root) |
| 836 |
b'<root>data</root>' |
| 837 |
|
| 838 |
The reasoning behind this difference is that ``parse()`` returns a |
| 839 |
complete document from a file, while the string parsing functions are |
| 840 |
commonly used to parse XML fragments. |
| 841 |
|
| 842 |
The ``parse()`` function supports any of the following sources: |
| 843 |
|
| 844 |
* an open file object (make sure to open it in binary mode) |
| 845 |
|
| 846 |
* a file-like object that has a ``.read(byte_count)`` method returning |
| 847 |
a byte string on each call |
| 848 |
|
| 849 |
* a filename string |
| 850 |
|
| 851 |
* an HTTP or FTP URL string |
| 852 |
|
| 853 |
Note that passing a filename or URL is usually faster than passing an |
| 854 |
open file or file-like object. However, the HTTP/FTP client in libxml2 |
| 855 |
is rather simple, so things like HTTP authentication require a dedicated |
| 856 |
URL request library, e.g. ``urllib2`` or ``requests``. These libraries |
| 857 |
usually provide a file-like object for the result that you can parse |
| 858 |
from while the response is streaming in. |
| 859 |
|
| 860 |
|
| 861 |
Parser objects |
| 862 |
-------------- |
| 863 |
|
| 864 |
By default, ``lxml.etree`` uses a standard parser with a default setup. If |
| 865 |
you want to configure the parser, you can create a new instance: |
| 866 |
|
| 867 |
.. sourcecode:: pycon |
| 868 |
|
| 869 |
>>> parser = etree.XMLParser(remove_blank_text=True) # lxml.etree only! |
| 870 |
|
| 871 |
This creates a parser that removes empty text between tags while parsing, |
| 872 |
which can reduce the size of the tree and avoid dangling tail text if you know |
| 873 |
that whitespace-only content is not meaningful for your data. An example: |
| 874 |
|
| 875 |
.. sourcecode:: pycon |
| 876 |
|
| 877 |
>>> root = etree.XML("<root> <a/> <b> </b> </root>", parser) |
| 878 |
|
| 879 |
>>> etree.tostring(root) |
| 880 |
b'<root><a/><b> </b></root>' |
| 881 |
|
| 882 |
Note that the whitespace content inside the ``<b>`` tag was not removed, as |
| 883 |
content at leaf elements tends to be data content (even if blank). You can |
| 884 |
easily remove it in an additional step by traversing the tree: |
| 885 |
|
| 886 |
.. sourcecode:: pycon |
| 887 |
|
| 888 |
>>> for element in root.iter("*"): |
| 889 |
... if element.text is not None and not element.text.strip(): |
| 890 |
... element.text = None |
| 891 |
|
| 892 |
>>> etree.tostring(root) |
| 893 |
b'<root><a/><b/></root>' |
| 894 |
|
| 895 |
See ``help(etree.XMLParser)`` to find out about the available parser options. |
| 896 |
|
| 897 |
|
| 898 |
Incremental parsing |
| 899 |
------------------- |
| 900 |
|
| 901 |
``lxml.etree`` provides two ways for incremental step-by-step parsing. One is |
| 902 |
through file-like objects, where it calls the ``read()`` method repeatedly. |
| 903 |
This is best used where the data arrives from a source like ``urllib`` or any |
| 904 |
other file-like object that can provide data on request. Note that the parser |
| 905 |
will block and wait until data becomes available in this case: |
| 906 |
|
| 907 |
.. sourcecode:: pycon |
| 908 |
|
| 909 |
>>> class DataSource: |
| 910 |
... data = [ b"<roo", b"t><", b"a/", b"><", b"/root>" ] |
| 911 |
... def read(self, requested_size): |
| 912 |
... try: |
| 913 |
... return self.data.pop(0) |
| 914 |
... except IndexError: |
| 915 |
... return b'' |
| 916 |
|
| 917 |
>>> tree = etree.parse(DataSource()) |
| 918 |
|
| 919 |
>>> etree.tostring(tree) |
| 920 |
b'<root><a/></root>' |
| 921 |
|
| 922 |
The second way is through a feed parser interface, given by the ``feed(data)`` |
| 923 |
and ``close()`` methods: |
| 924 |
|
| 925 |
.. sourcecode:: pycon |
| 926 |
|
| 927 |
>>> parser = etree.XMLParser() |
| 928 |
|
| 929 |
>>> parser.feed("<roo") |
| 930 |
>>> parser.feed("t><") |
| 931 |
>>> parser.feed("a/") |
| 932 |
>>> parser.feed("><") |
| 933 |
>>> parser.feed("/root>") |
| 934 |
|
| 935 |
>>> root = parser.close() |
| 936 |
|
| 937 |
>>> etree.tostring(root) |
| 938 |
b'<root><a/></root>' |
| 939 |
|
| 940 |
Here, you can interrupt the parsing process at any time and continue it later |
| 941 |
on with another call to the ``feed()`` method. This comes in handy if you |
| 942 |
want to avoid blocking calls to the parser, e.g. in frameworks like Twisted, |
| 943 |
or whenever data comes in slowly or in chunks and you want to do other things |
| 944 |
while waiting for the next chunk. |
| 945 |
|
| 946 |
After calling the ``close()`` method (or when an exception was raised |
| 947 |
by the parser), you can reuse the parser by calling its ``feed()`` |
| 948 |
method again: |
| 949 |
|
| 950 |
.. sourcecode:: pycon |
| 951 |
|
| 952 |
>>> parser.feed("<root/>") |
| 953 |
>>> root = parser.close() |
| 954 |
>>> etree.tostring(root) |
| 955 |
b'<root/>' |
| 956 |
|
| 957 |
|
| 958 |
Event-driven parsing |
| 959 |
-------------------- |
| 960 |
|
| 961 |
Sometimes, all you need from a document is a small fraction somewhere deep |
| 962 |
inside the tree, so parsing the whole tree into memory, traversing it and |
| 963 |
dropping it can be too much overhead. ``lxml.etree`` supports this use case |
| 964 |
with two event-driven parser interfaces, one that generates parser events |
| 965 |
while building the tree (``iterparse``), and one that does not build the tree |
| 966 |
at all, and instead calls feedback methods on a target object in a SAX-like |
| 967 |
fashion. |
| 968 |
|
| 969 |
Here is a simple ``iterparse()`` example: |
| 970 |
|
| 971 |
.. sourcecode:: pycon |
| 972 |
|
| 973 |
>>> some_file_like = BytesIO(b"<root><a>data</a></root>") |
| 974 |
|
| 975 |
>>> for event, element in etree.iterparse(some_file_like): |
| 976 |
... print(f"{event}, {element.tag:>4}, {element.text}") |
| 977 |
end, a, data |
| 978 |
end, root, None |
| 979 |
|
| 980 |
By default, ``iterparse()`` only generates an event when it is done parsing an |
| 981 |
element, but you can control this through the ``events`` keyword argument: |
| 982 |
|
| 983 |
.. sourcecode:: pycon |
| 984 |
|
| 985 |
>>> some_file_like = BytesIO(b"<root><a>data</a></root>") |
| 986 |
|
| 987 |
>>> for event, element in etree.iterparse(some_file_like, |
| 988 |
... events=("start", "end")): |
| 989 |
... print(f"{event:>5}, {element.tag:>4}, {element.text}") |
| 990 |
start, root, None |
| 991 |
start, a, data |
| 992 |
end, a, data |
| 993 |
end, root, None |
| 994 |
|
| 995 |
Note that the text, tail, and children of an Element are not necessarily present |
| 996 |
yet when receiving the ``start`` event. Only the ``end`` event guarantees |
| 997 |
that the Element has been parsed completely. |
| 998 |
|
| 999 |
It also allows you to ``.clear()`` or modify the content of an Element to |
| 1000 |
save memory. So if you parse a large tree and you want to keep memory |
| 1001 |
usage small, you should clean up parts of the tree that you no longer |
| 1002 |
need. The ``keep_tail=True`` argument to ``.clear()`` makes sure that |
| 1003 |
(tail) text content that follows the current element will not be touched. |
| 1004 |
It is highly discouraged to modify any content that the parser may not |
| 1005 |
have completely read through yet. |
| 1006 |
|
| 1007 |
.. sourcecode:: pycon |
| 1008 |
|
| 1009 |
>>> some_file_like = BytesIO( |
| 1010 |
... b"<root><a><b>data</b></a><a><b/></a></root>") |
| 1011 |
|
| 1012 |
>>> for event, element in etree.iterparse(some_file_like): |
| 1013 |
... if element.tag == 'b': |
| 1014 |
... print(element.text) |
| 1015 |
... elif element.tag == 'a': |
| 1016 |
... print("** cleaning up the subtree") |
| 1017 |
... element.clear(keep_tail=True) |
| 1018 |
data |
| 1019 |
** cleaning up the subtree |
| 1020 |
None |
| 1021 |
** cleaning up the subtree |
| 1022 |
|
| 1023 |
A very important use case for ``iterparse()`` is parsing large |
| 1024 |
generated XML files, e.g. database dumps. Most often, these XML |
| 1025 |
formats only have one main data item element that hangs directly below |
| 1026 |
the root node and that is repeated thousands of times. In this case, |
| 1027 |
it is best practice to let ``lxml.etree`` do the tree building and only to |
| 1028 |
intercept on exactly this one Element, using the normal tree API |
| 1029 |
for data extraction. |
| 1030 |
|
| 1031 |
.. sourcecode:: pycon |
| 1032 |
|
| 1033 |
>>> xml_file = BytesIO(b'''\ |
| 1034 |
... <root> |
| 1035 |
... <a><b>ABC</b><c>abc</c></a> |
| 1036 |
... <a><b>MORE DATA</b><c>more data</c></a> |
| 1037 |
... <a><b>XYZ</b><c>xyz</c></a> |
| 1038 |
... </root>''') |
| 1039 |
|
| 1040 |
>>> for _, element in etree.iterparse(xml_file, tag='a'): |
| 1041 |
... print('%s -- %s' % (element.findtext('b'), element[1].text)) |
| 1042 |
... element.clear(keep_tail=True) |
| 1043 |
ABC -- abc |
| 1044 |
MORE DATA -- more data |
| 1045 |
XYZ -- xyz |
| 1046 |
|
| 1047 |
If, for some reason, building the tree is not desired at all, the |
| 1048 |
target parser interface of ``lxml.etree`` can be used. It creates |
| 1049 |
SAX-like events by calling the methods of a target object. By |
| 1050 |
implementing some or all of these methods, you can control which |
| 1051 |
events are generated: |
| 1052 |
|
| 1053 |
.. sourcecode:: pycon |
| 1054 |
|
| 1055 |
>>> class ParserTarget: |
| 1056 |
... events = [] |
| 1057 |
... close_count = 0 |
| 1058 |
... def start(self, tag, attrib): |
| 1059 |
... self.events.append(("start", tag, attrib)) |
| 1060 |
... def close(self): |
| 1061 |
... events, self.events = self.events, [] |
| 1062 |
... self.close_count += 1 |
| 1063 |
... return events |
| 1064 |
|
| 1065 |
>>> parser_target = ParserTarget() |
| 1066 |
|
| 1067 |
>>> parser = etree.XMLParser(target=parser_target) |
| 1068 |
>>> events = etree.fromstring('<root test="true"/>', parser) |
| 1069 |
|
| 1070 |
>>> print(parser_target.close_count) |
| 1071 |
1 |
| 1072 |
|
| 1073 |
>>> for event in events: |
| 1074 |
... print(f'event: {event[0]} - tag: {event[1]}') |
| 1075 |
... for attr, value in event[2].items(): |
| 1076 |
... print(f' * {attr} = {value}') |
| 1077 |
event: start - tag: root |
| 1078 |
* test = true |
| 1079 |
|
| 1080 |
You can reuse the parser and its target as often as you like, so you |
| 1081 |
should take care that the ``.close()`` method really resets the |
| 1082 |
target to a usable state (also in the case of an error!). |
| 1083 |
|
| 1084 |
.. sourcecode:: pycon |
| 1085 |
|
| 1086 |
>>> events = etree.fromstring('<root test="true"/>', parser) |
| 1087 |
>>> print(parser_target.close_count) |
| 1088 |
2 |
| 1089 |
>>> events = etree.fromstring('<root test="true"/>', parser) |
| 1090 |
>>> print(parser_target.close_count) |
| 1091 |
3 |
| 1092 |
>>> events = etree.fromstring('<root test="true"/>', parser) |
| 1093 |
>>> print(parser_target.close_count) |
| 1094 |
4 |
| 1095 |
|
| 1096 |
>>> for event in events: |
| 1097 |
... print(f'event: {event[0]} - tag: {event[1]}') |
| 1098 |
... for attr, value in event[2].items(): |
| 1099 |
... print(f' * {attr} = {value}') |
| 1100 |
event: start - tag: root |
| 1101 |
* test = true |
| 1102 |
|
| 1103 |
|
| 1104 |
Namespaces |
| 1105 |
========== |
| 1106 |
|
| 1107 |
The ElementTree API avoids |
| 1108 |
`namespace prefixes <http://www.w3.org/TR/xml-names/#ns-qualnames>`_ |
| 1109 |
wherever possible and deploys the real namespace (the URI) instead: |
| 1110 |
|
| 1111 |
.. sourcecode:: pycon |
| 1112 |
|
| 1113 |
>>> xhtml = etree.Element("{http://www.w3.org/1999/xhtml}html") |
| 1114 |
>>> body = etree.SubElement(xhtml, "{http://www.w3.org/1999/xhtml}body") |
| 1115 |
>>> body.text = "Hello World" |
| 1116 |
|
| 1117 |
>>> prettyprint(xhtml) |
| 1118 |
<html:html xmlns:html="http://www.w3.org/1999/xhtml"> |
| 1119 |
<html:body>Hello World</html:body> |
| 1120 |
</html:html> |
| 1121 |
|
| 1122 |
The notation that ElementTree uses was originally brought up by |
| 1123 |
`James Clark <http://www.jclark.com/xml/xmlns.htm>`_. It has the major |
| 1124 |
advantage of providing a universally qualified name for a tag, regardless |
| 1125 |
of any prefixes that may or may not have been used or defined in a document. |
| 1126 |
By moving the indirection of prefixes out of the way, it makes namespace |
| 1127 |
aware code much clearer and easier to get right. |
| 1128 |
|
| 1129 |
As you can see from the example, prefixes only become important when |
| 1130 |
you serialise the result. However, the above code looks somewhat |
| 1131 |
verbose due to the lengthy namespace names. And retyping or copying a |
| 1132 |
string over and over again is error prone. It is therefore common |
| 1133 |
practice to store a namespace URI in a global variable. To adapt the |
| 1134 |
namespace prefixes for serialisation, you can also pass a mapping to |
| 1135 |
the Element factory function, e.g. to define the default namespace: |
| 1136 |
|
| 1137 |
.. sourcecode:: pycon |
| 1138 |
|
| 1139 |
>>> XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml" |
| 1140 |
>>> XHTML = "{%s}" % XHTML_NAMESPACE |
| 1141 |
|
| 1142 |
>>> NSMAP = {None : XHTML_NAMESPACE} # the default namespace (no prefix) |
| 1143 |
|
| 1144 |
>>> xhtml = etree.Element(XHTML + "html", nsmap=NSMAP) # lxml only! |
| 1145 |
>>> body = etree.SubElement(xhtml, XHTML + "body") |
| 1146 |
>>> body.text = "Hello World" |
| 1147 |
|
| 1148 |
>>> prettyprint(xhtml) |
| 1149 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
| 1150 |
<body>Hello World</body> |
| 1151 |
</html> |
| 1152 |
|
| 1153 |
You can also use the ``QName`` helper class to build or split qualified |
| 1154 |
tag names: |
| 1155 |
|
| 1156 |
.. sourcecode:: pycon |
| 1157 |
|
| 1158 |
>>> tag = etree.QName('http://www.w3.org/1999/xhtml', 'html') |
| 1159 |
>>> print(tag.localname) |
| 1160 |
html |
| 1161 |
>>> print(tag.namespace) |
| 1162 |
http://www.w3.org/1999/xhtml |
| 1163 |
>>> print(tag.text) |
| 1164 |
{http://www.w3.org/1999/xhtml}html |
| 1165 |
|
| 1166 |
>>> tag = etree.QName('{http://www.w3.org/1999/xhtml}html') |
| 1167 |
>>> print(tag.localname) |
| 1168 |
html |
| 1169 |
>>> print(tag.namespace) |
| 1170 |
http://www.w3.org/1999/xhtml |
| 1171 |
|
| 1172 |
>>> root = etree.Element('{http://www.w3.org/1999/xhtml}html') |
| 1173 |
>>> tag = etree.QName(root) |
| 1174 |
>>> print(tag.localname) |
| 1175 |
html |
| 1176 |
|
| 1177 |
>>> tag = etree.QName(root, 'script') |
| 1178 |
>>> print(tag.text) |
| 1179 |
{http://www.w3.org/1999/xhtml}script |
| 1180 |
>>> tag = etree.QName('{http://www.w3.org/1999/xhtml}html', 'script') |
| 1181 |
>>> print(tag.text) |
| 1182 |
{http://www.w3.org/1999/xhtml}script |
| 1183 |
|
| 1184 |
lxml.etree allows you to look up the current namespaces defined for a |
| 1185 |
node through the ``.nsmap`` property: |
| 1186 |
|
| 1187 |
.. sourcecode:: pycon |
| 1188 |
|
| 1189 |
>>> xhtml.nsmap |
| 1190 |
{None: 'http://www.w3.org/1999/xhtml'} |
| 1191 |
|
| 1192 |
Note, however, that this includes all prefixes known in the context of |
| 1193 |
an Element, not only those that it defines itself. |
| 1194 |
|
| 1195 |
.. sourcecode:: pycon |
| 1196 |
|
| 1197 |
>>> root = etree.Element('root', nsmap={'a': 'http://a.b/c'}) |
| 1198 |
>>> child = etree.SubElement(root, 'child', |
| 1199 |
... nsmap={'b': 'http://b.c/d'}) |
| 1200 |
>>> len(root.nsmap) |
| 1201 |
1 |
| 1202 |
>>> len(child.nsmap) |
| 1203 |
2 |
| 1204 |
>>> child.nsmap['a'] |
| 1205 |
'http://a.b/c' |
| 1206 |
>>> child.nsmap['b'] |
| 1207 |
'http://b.c/d' |
| 1208 |
|
| 1209 |
Therefore, modifying the returned dict cannot have any meaningful |
| 1210 |
impact on the Element. Any changes to it are ignored. |
| 1211 |
|
| 1212 |
Namespaces on attributes work alike, but as of version 2.3, ``lxml.etree`` |
| 1213 |
will ensure that the attribute uses a prefixed namespace |
| 1214 |
declaration. This is because unprefixed attribute names are not |
| 1215 |
considered being in a namespace by the XML namespace specification |
| 1216 |
(`section 6.2`_), so they may end up losing their namespace on a |
| 1217 |
serialise-parse roundtrip, even if they appear in a namespaced |
| 1218 |
element. |
| 1219 |
|
| 1220 |
.. sourcecode:: pycon |
| 1221 |
|
| 1222 |
>>> body.set(XHTML + "bgcolor", "#CCFFAA") |
| 1223 |
|
| 1224 |
>>> prettyprint(xhtml) |
| 1225 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
| 1226 |
<body xmlns:html="http://www.w3.org/1999/xhtml" html:bgcolor="#CCFFAA">Hello World</body> |
| 1227 |
</html> |
| 1228 |
|
| 1229 |
>>> print(body.get("bgcolor")) |
| 1230 |
None |
| 1231 |
>>> body.get(XHTML + "bgcolor") |
| 1232 |
'#CCFFAA' |
| 1233 |
|
| 1234 |
.. _`section 6.2`: http://www.w3.org/TR/2009/REC-xml-names-20091208/#defaulting |
| 1235 |
|
| 1236 |
You can also use XPath with fully qualified names: |
| 1237 |
|
| 1238 |
.. sourcecode:: pycon |
| 1239 |
|
| 1240 |
>>> find_xhtml_body = etree.ETXPath( # lxml only ! |
| 1241 |
... "//{%s}body" % XHTML_NAMESPACE) |
| 1242 |
>>> results = find_xhtml_body(xhtml) |
| 1243 |
|
| 1244 |
>>> print(results[0].tag) |
| 1245 |
{http://www.w3.org/1999/xhtml}body |
| 1246 |
|
| 1247 |
For convenience, you can use ``"*"`` wildcards in all iterators of ``lxml.etree``, |
| 1248 |
both for tag names and namespaces: |
| 1249 |
|
| 1250 |
.. sourcecode:: pycon |
| 1251 |
|
| 1252 |
>>> for el in xhtml.iter('*'): print(el.tag) # any element |
| 1253 |
{http://www.w3.org/1999/xhtml}html |
| 1254 |
{http://www.w3.org/1999/xhtml}body |
| 1255 |
|
| 1256 |
>>> for el in xhtml.iter('{http://www.w3.org/1999/xhtml}*'): print(el.tag) |
| 1257 |
{http://www.w3.org/1999/xhtml}html |
| 1258 |
{http://www.w3.org/1999/xhtml}body |
| 1259 |
|
| 1260 |
>>> for el in xhtml.iter('{*}body'): print(el.tag) |
| 1261 |
{http://www.w3.org/1999/xhtml}body |
| 1262 |
|
| 1263 |
To look for elements that do not have a namespace, either use the |
| 1264 |
plain tag name or provide the empty namespace explicitly: |
| 1265 |
|
| 1266 |
.. sourcecode:: pycon |
| 1267 |
|
| 1268 |
>>> [ el.tag for el in xhtml.iter('{http://www.w3.org/1999/xhtml}body') ] |
| 1269 |
['{http://www.w3.org/1999/xhtml}body'] |
| 1270 |
>>> [ el.tag for el in xhtml.iter('body') ] |
| 1271 |
[] |
| 1272 |
>>> [ el.tag for el in xhtml.iter('{}body') ] |
| 1273 |
[] |
| 1274 |
>>> [ el.tag for el in xhtml.iter('{}*') ] |
| 1275 |
[] |
| 1276 |
|
| 1277 |
|
| 1278 |
The E-factory |
| 1279 |
============= |
| 1280 |
|
| 1281 |
The ``E-factory`` provides a simple and compact syntax for generating XML and |
| 1282 |
HTML: |
| 1283 |
|
| 1284 |
.. sourcecode:: pycon |
| 1285 |
|
| 1286 |
>>> from lxml.builder import E |
| 1287 |
|
| 1288 |
>>> def CLASS(*args): # class is a reserved word in Python |
| 1289 |
... return {"class":' '.join(args)} |
| 1290 |
|
| 1291 |
>>> html = page = ( |
| 1292 |
... E.html( # create an Element called "html" |
| 1293 |
... E.head( |
| 1294 |
... E.title("This is a sample document") |
| 1295 |
... ), |
| 1296 |
... E.body( |
| 1297 |
... E.h1("Hello!", CLASS("title")), |
| 1298 |
... E.p("This is a paragraph with ", E.b("bold"), " text in it!"), |
| 1299 |
... E.p("This is another paragraph, with a", "\n ", |
| 1300 |
... E.a("link", href="http://www.python.org"), "."), |
| 1301 |
... E.p("Here are some reserved characters: <spam&egg>."), |
| 1302 |
... etree.XML("<p>And finally an embedded XHTML fragment.</p>"), |
| 1303 |
... ) |
| 1304 |
... ) |
| 1305 |
... ) |
| 1306 |
|
| 1307 |
>>> prettyprint(page) |
| 1308 |
<html> |
| 1309 |
<head> |
| 1310 |
<title>This is a sample document</title> |
| 1311 |
</head> |
| 1312 |
<body> |
| 1313 |
<h1 class="title">Hello!</h1> |
| 1314 |
<p>This is a paragraph with <b>bold</b> text in it!</p> |
| 1315 |
<p>This is another paragraph, with a |
| 1316 |
<a href="http://www.python.org">link</a>.</p> |
| 1317 |
<p>Here are some reserved characters: <spam&egg>.</p> |
| 1318 |
<p>And finally an embedded XHTML fragment.</p> |
| 1319 |
</body> |
| 1320 |
</html> |
| 1321 |
|
| 1322 |
Element creation based on attribute access makes it easy to build up a |
| 1323 |
simple vocabulary for an XML language: |
| 1324 |
|
| 1325 |
.. sourcecode:: pycon |
| 1326 |
|
| 1327 |
>>> from lxml.builder import ElementMaker # lxml only ! |
| 1328 |
|
| 1329 |
>>> E = ElementMaker(namespace="http://my.de/fault/namespace", |
| 1330 |
... nsmap={'p' : "http://my.de/fault/namespace"}) |
| 1331 |
|
| 1332 |
>>> DOC = E.doc |
| 1333 |
>>> TITLE = E.title |
| 1334 |
>>> SECTION = E.section |
| 1335 |
>>> PAR = E.par |
| 1336 |
|
| 1337 |
>>> my_doc = DOC( |
| 1338 |
... TITLE("The dog and the hog"), |
| 1339 |
... SECTION( |
| 1340 |
... TITLE("The dog"), |
| 1341 |
... PAR("Once upon a time, ..."), |
| 1342 |
... PAR("And then ...") |
| 1343 |
... ), |
| 1344 |
... SECTION( |
| 1345 |
... TITLE("The hog"), |
| 1346 |
... PAR("Sooner or later ...") |
| 1347 |
... ) |
| 1348 |
... ) |
| 1349 |
|
| 1350 |
>>> prettyprint(my_doc) |
| 1351 |
<p:doc xmlns:p="http://my.de/fault/namespace"> |
| 1352 |
<p:title>The dog and the hog</p:title> |
| 1353 |
<p:section> |
| 1354 |
<p:title>The dog</p:title> |
| 1355 |
<p:par>Once upon a time, ...</p:par> |
| 1356 |
<p:par>And then ...</p:par> |
| 1357 |
</p:section> |
| 1358 |
<p:section> |
| 1359 |
<p:title>The hog</p:title> |
| 1360 |
<p:par>Sooner or later ...</p:par> |
| 1361 |
</p:section> |
| 1362 |
</p:doc> |
| 1363 |
|
| 1364 |
One such example is the module ``lxml.html.builder``, which provides a |
| 1365 |
vocabulary for HTML. |
| 1366 |
|
| 1367 |
When dealing with multiple namespaces, it is good practice to define |
| 1368 |
one ElementMaker for each namespace URI. Again, note how the above |
| 1369 |
example predefines the tag builders in named constants. That makes it |
| 1370 |
easy to put all tag declarations of a namespace into one Python module |
| 1371 |
and to import/use the tag name constants from there. This avoids |
| 1372 |
pitfalls like typos or accidentally missing namespaces. |
| 1373 |
|
| 1374 |
|
| 1375 |
ElementPath |
| 1376 |
=========== |
| 1377 |
|
| 1378 |
The ElementTree library comes with a simple XPath-like path language |
| 1379 |
called ElementPath_. The main difference is that you can use the |
| 1380 |
``{namespace}tag`` notation in ElementPath expressions. However, |
| 1381 |
advanced features like value comparison and functions are not |
| 1382 |
available. |
| 1383 |
|
| 1384 |
.. _ElementPath: https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support |
| 1385 |
.. _`full XPath implementation`: xpathxslt.html#xpath |
| 1386 |
|
| 1387 |
ElementPath was `originally implemented |
| 1388 |
<https://web.archive.org/web/20070920063445/http://www.effbot.org/zone/element-xpath.htm>`_ |
| 1389 |
by Fredrik Lundh |
| 1390 |
|
| 1391 |
In addition to a `full XPath implementation`_, ``lxml.etree`` supports the |
| 1392 |
ElementPath language in the same way ElementTree does, even using |
| 1393 |
(almost) the same implementation. The API provides four methods here |
| 1394 |
that you can find on Elements and ElementTrees: |
| 1395 |
|
| 1396 |
* ``iterfind()`` iterates over all Elements that match the path |
| 1397 |
expression |
| 1398 |
|
| 1399 |
* ``findall()`` returns a list of matching Elements |
| 1400 |
|
| 1401 |
* ``find()`` efficiently returns only the first match |
| 1402 |
|
| 1403 |
* ``findtext()`` returns the ``.text`` content of the first match |
| 1404 |
|
| 1405 |
Here are some examples: |
| 1406 |
|
| 1407 |
.. sourcecode:: pycon |
| 1408 |
|
| 1409 |
>>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>") |
| 1410 |
|
| 1411 |
Find a child of an Element: |
| 1412 |
|
| 1413 |
.. sourcecode:: pycon |
| 1414 |
|
| 1415 |
>>> print(root.find("b")) |
| 1416 |
None |
| 1417 |
>>> print(root.find("a").tag) |
| 1418 |
a |
| 1419 |
|
| 1420 |
Find an Element anywhere in the tree: |
| 1421 |
|
| 1422 |
.. sourcecode:: pycon |
| 1423 |
|
| 1424 |
>>> print(root.find(".//b").tag) |
| 1425 |
b |
| 1426 |
>>> [ b.tag for b in root.iterfind(".//b") ] |
| 1427 |
['b', 'b'] |
| 1428 |
|
| 1429 |
Find Elements with a certain attribute: |
| 1430 |
|
| 1431 |
.. sourcecode:: pycon |
| 1432 |
|
| 1433 |
>>> print(root.findall(".//a[@x]")[0].tag) |
| 1434 |
a |
| 1435 |
>>> print(root.findall(".//a[@y]")) |
| 1436 |
[] |
| 1437 |
|
| 1438 |
In lxml 3.4, there is a new helper to generate a structural ElementPath |
| 1439 |
expression for an Element: |
| 1440 |
|
| 1441 |
.. sourcecode:: pycon |
| 1442 |
|
| 1443 |
>>> tree = etree.ElementTree(root) |
| 1444 |
>>> a = root[0] |
| 1445 |
>>> print(tree.getelementpath(a[0])) |
| 1446 |
a/b[1] |
| 1447 |
>>> print(tree.getelementpath(a[1])) |
| 1448 |
a/c |
| 1449 |
>>> print(tree.getelementpath(a[2])) |
| 1450 |
a/b[2] |
| 1451 |
>>> tree.find(tree.getelementpath(a[2])) == a[2] |
| 1452 |
True |
| 1453 |
|
| 1454 |
As long as the tree is not modified, this path expression represents an |
| 1455 |
identifier for a given element that can be used to ``find()`` it in the same |
| 1456 |
tree later. Compared to XPath, ElementPath expressions have the advantage |
| 1457 |
of being self-contained even for documents that use namespaces. |
| 1458 |
|
| 1459 |
The ``.iter()`` method is a special case that only finds specific tags |
| 1460 |
in the tree by their name, not based on a path. That means that the |
| 1461 |
following commands are equivalent in the success case: |
| 1462 |
|
| 1463 |
.. sourcecode:: pycon |
| 1464 |
|
| 1465 |
>>> print(root.find(".//b").tag) |
| 1466 |
b |
| 1467 |
>>> print(next(root.iterfind(".//b")).tag) |
| 1468 |
b |
| 1469 |
>>> print(next(root.iter("b")).tag) |
| 1470 |
b |
| 1471 |
|
| 1472 |
Note that the ``.find()`` method simply returns None if no match is found, |
| 1473 |
whereas the other two examples would raise a ``StopIteration`` exception. |