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