| 1 |
==================================== |
| 2 |
Implementing XML languages with lxml |
| 3 |
==================================== |
| 4 |
|
| 5 |
Dr. Stefan Behnel |
| 6 |
----------------- |
| 7 |
|
| 8 |
.. class:: center |
| 9 |
|
| 10 |
http://codespeak.net/lxml/ |
| 11 |
|
| 12 |
[email protected] |
| 13 |
|
| 14 |
.. image:: tagpython.png |
| 15 |
|
| 16 |
.. footer:: Dr. Stefan Behnel, EuroPython 2008, Vilnius/Lietuva |
| 17 |
|
| 18 |
.. include:: <s5defs.txt> |
| 19 |
|
| 20 |
|
| 21 |
What is an »XML language«? |
| 22 |
========================== |
| 23 |
|
| 24 |
* a language in XML notation |
| 25 |
|
| 26 |
* aka »XML dialect« |
| 27 |
|
| 28 |
* except that it's not a dialect |
| 29 |
|
| 30 |
* Examples: |
| 31 |
|
| 32 |
* XML Schema |
| 33 |
|
| 34 |
* Atom/RSS |
| 35 |
|
| 36 |
* (X)HTML |
| 37 |
|
| 38 |
* Open Document Format |
| 39 |
|
| 40 |
* SOAP |
| 41 |
|
| 42 |
* ... add your own one here |
| 43 |
|
| 44 |
|
| 45 |
Popular mistakes to avoid (1) |
| 46 |
============================= |
| 47 |
|
| 48 |
"That's easy, I can use regular expressions!" |
| 49 |
|
| 50 |
.. class:: incremental center |
| 51 |
|
| 52 |
No, you can't. |
| 53 |
|
| 54 |
|
| 55 |
Popular mistakes to avoid (2) |
| 56 |
============================= |
| 57 |
|
| 58 |
"This is tree data, I'll take the DOM!" |
| 59 |
|
| 60 |
|
| 61 |
Popular mistakes to avoid (2) |
| 62 |
============================= |
| 63 |
|
| 64 |
"This is tree data, I'll take the DOM!" |
| 65 |
|
| 66 |
* DOM is ubiquitous, but it's as complicated as Java |
| 67 |
|
| 68 |
* uglify your application with tons of DOM code to |
| 69 |
|
| 70 |
* walk over non-element nodes to find the data you need |
| 71 |
|
| 72 |
* convert text content to other data types |
| 73 |
|
| 74 |
* modify the XML tree in memory |
| 75 |
|
| 76 |
=> write verbose, redundant, hard-to-maintain code |
| 77 |
|
| 78 |
|
| 79 |
Popular mistakes to avoid (3) |
| 80 |
============================= |
| 81 |
|
| 82 |
"SAX is *so* fast and consumes *no* memory!" |
| 83 |
|
| 84 |
|
| 85 |
Popular mistakes to avoid (3) |
| 86 |
============================= |
| 87 |
|
| 88 |
"SAX is *so* fast and consumes *no* memory!" |
| 89 |
|
| 90 |
* but *writing* SAX code is *not* fast! |
| 91 |
|
| 92 |
* write error-prone, state-keeping SAX code to |
| 93 |
|
| 94 |
* figure out where you are |
| 95 |
|
| 96 |
* find the sections you need |
| 97 |
|
| 98 |
* convert text content to other data types |
| 99 |
|
| 100 |
* copy the XML data into custom data classes |
| 101 |
|
| 102 |
* ... and don't forget the way back into XML! |
| 103 |
|
| 104 |
=> write confusing state-machine code |
| 105 |
|
| 106 |
=> debugging into existence |
| 107 |
|
| 108 |
|
| 109 |
Working with XML |
| 110 |
================ |
| 111 |
|
| 112 |
**Getting XML work done** |
| 113 |
|
| 114 |
(instead of getting time wasted) |
| 115 |
|
| 116 |
|
| 117 |
How can you work with XML? |
| 118 |
========================== |
| 119 |
|
| 120 |
* Preparation: |
| 121 |
|
| 122 |
* Implement usable data classes as an abstraction layer |
| 123 |
|
| 124 |
* Implement a mapping from XML to the data classes |
| 125 |
|
| 126 |
* Implement a mapping from the data classes to XML |
| 127 |
|
| 128 |
* Workflow: |
| 129 |
|
| 130 |
* parse XML data |
| 131 |
|
| 132 |
* map XML data to data classes |
| 133 |
|
| 134 |
* work with data classes |
| 135 |
|
| 136 |
* map data classes to XML |
| 137 |
|
| 138 |
* serialise XML |
| 139 |
|
| 140 |
.. class:: incremental |
| 141 |
|
| 142 |
* Approach: |
| 143 |
|
| 144 |
* get rid of XML and do everything in your own code |
| 145 |
|
| 146 |
|
| 147 |
What if you could simplify this? |
| 148 |
================================ |
| 149 |
|
| 150 |
* Preparation: |
| 151 |
|
| 152 |
* Extend usable XML API classes into an abstraction layer |
| 153 |
|
| 154 |
* Workflow: |
| 155 |
|
| 156 |
* parse XML data into XML API classes |
| 157 |
|
| 158 |
* work with XML API classes |
| 159 |
|
| 160 |
* serialise XML |
| 161 |
|
| 162 |
.. class:: incremental |
| 163 |
|
| 164 |
* Approach: |
| 165 |
|
| 166 |
* cover only the quirks of XML and make it work *for* you |
| 167 |
|
| 168 |
|
| 169 |
What if you could simplify this ... |
| 170 |
=================================== |
| 171 |
|
| 172 |
* ... without sacrificing usability or flexibility? |
| 173 |
|
| 174 |
* ... using a high-speed, full-featured, pythonic XML toolkit? |
| 175 |
|
| 176 |
* ... with the power of XPath, XSLT and XML validation? |
| 177 |
|
| 178 |
.. class:: incremental center |
| 179 |
|
| 180 |
\... then »lxml« is your friend! |
| 181 |
|
| 182 |
|
| 183 |
Overview |
| 184 |
======== |
| 185 |
|
| 186 |
* What is lxml? |
| 187 |
|
| 188 |
* what & who |
| 189 |
|
| 190 |
* How do you use it? |
| 191 |
|
| 192 |
* Lesson 0: quick API overview |
| 193 |
|
| 194 |
* ElementTree concepts and lxml features |
| 195 |
|
| 196 |
* Lesson 1: parse XML |
| 197 |
|
| 198 |
* how to get XML data into memory |
| 199 |
|
| 200 |
* Lesson 2: generate XML |
| 201 |
|
| 202 |
* how to write an XML generator for a language |
| 203 |
|
| 204 |
* Lesson 3: working with XML trees made easy |
| 205 |
|
| 206 |
* how to write an XML API for a language |
| 207 |
|
| 208 |
|
| 209 |
What is lxml? |
| 210 |
============= |
| 211 |
|
| 212 |
* a fast, full-featured toolkit for XML and HTML handling |
| 213 |
|
| 214 |
* http://codespeak.net/lxml/ |
| 215 |
|
| 216 |
* [email protected] |
| 217 |
|
| 218 |
* based on and inspired by |
| 219 |
|
| 220 |
* the C libraries libxml2 and libxslt (by Daniel Veillard) |
| 221 |
|
| 222 |
* the ElementTree API (by Fredrik Lundh) |
| 223 |
|
| 224 |
* the Cython compiler (by Robert Bradshaw, Greg Ewing & me) |
| 225 |
|
| 226 |
* the Python language (by Guido & [*paste Misc/ACKS here*]) |
| 227 |
|
| 228 |
* user feedback, ideas and patches (by you!) |
| 229 |
|
| 230 |
* keep doing that, we love you all! |
| 231 |
|
| 232 |
* maintained (and major parts) written by myself |
| 233 |
|
| 234 |
* initial design and implementation by Martijn Faassen |
| 235 |
|
| 236 |
* extensive HTML API and tools by Ian Bicking |
| 237 |
|
| 238 |
|
| 239 |
What do you get for your money? |
| 240 |
=============================== |
| 241 |
|
| 242 |
* many tools in one: |
| 243 |
|
| 244 |
* Generic, ElementTree compatible XML API: **lxml.etree** |
| 245 |
|
| 246 |
* but faster for many tasks and much more feature-rich |
| 247 |
|
| 248 |
* Special tool set for HTML handling: **lxml.html** |
| 249 |
|
| 250 |
* Special API for pythonic data binding: **lxml.objectify** |
| 251 |
|
| 252 |
* General purpose path languages: XPath and CSS selectors |
| 253 |
|
| 254 |
* Validation: DTD, XML Schema, RelaxNG, Schematron |
| 255 |
|
| 256 |
* XSLT, XInclude, C14N, ... |
| 257 |
|
| 258 |
* Fast tree iteration, event-driven parsing, ... |
| 259 |
|
| 260 |
* it's free, but it's worth every €-Cent! |
| 261 |
|
| 262 |
* what users say: |
| 263 |
|
| 264 |
* »no qualification, I would recommend lxml for just about any |
| 265 |
HTML task« |
| 266 |
|
| 267 |
* »THE tool [...] for newbies and experienced developers« |
| 268 |
|
| 269 |
* »you can do pretty much anything with an intuitive API« |
| 270 |
|
| 271 |
* »lxml takes all the pain out of XML« |
| 272 |
|
| 273 |
|
| 274 |
Lesson 0: a quick overview |
| 275 |
========================== |
| 276 |
|
| 277 |
why **»lxml takes all the pain out of XML«** |
| 278 |
|
| 279 |
(a quick overview of lxml features and ElementTree concepts) |
| 280 |
|
| 281 |
.. |
| 282 |
>>> from lxml import etree, cssselect, html |
| 283 |
>>> some_xml_data = "<root><speech class='dialog'><p>So be it!</p></speech><p>stuff</p></root>" |
| 284 |
>>> some_html_data = "<p>Just a quick note<br>next line</p>" |
| 285 |
>>> xml_tree = etree.XML(some_xml_data) |
| 286 |
>>> html_tree = html.fragment_fromstring(some_html_data) |
| 287 |
|
| 288 |
|
| 289 |
Namespaces in ElementTree |
| 290 |
========================= |
| 291 |
|
| 292 |
* uses Clark notation: |
| 293 |
|
| 294 |
* wrap namespace URI in ``{...}`` |
| 295 |
|
| 296 |
* append the tag name |
| 297 |
|
| 298 |
.. sourcecode:: pycon |
| 299 |
|
| 300 |
>>> tag = "{http://www.w3.org/the/namespace}tagname" |
| 301 |
>>> element = etree.Element(tag) |
| 302 |
|
| 303 |
* no prefixes! |
| 304 |
|
| 305 |
* a single, self-containing tag identifier |
| 306 |
|
| 307 |
|
| 308 |
Text content in ElementTree |
| 309 |
=========================== |
| 310 |
|
| 311 |
* uses ``.text`` and ``.tail`` attributes: |
| 312 |
|
| 313 |
.. sourcecode:: pycon |
| 314 |
|
| 315 |
>>> div = html.fragment_fromstring( |
| 316 |
... "<div><p>a paragraph<br>split in two</p> parts</div>") |
| 317 |
>>> p = div[0] |
| 318 |
>>> br = p[0] |
| 319 |
|
| 320 |
>>> p.text |
| 321 |
'a paragraph' |
| 322 |
>>> br.text |
| 323 |
>>> br.tail |
| 324 |
'split in two' |
| 325 |
>>> p.tail |
| 326 |
' parts' |
| 327 |
|
| 328 |
* no text nodes! |
| 329 |
|
| 330 |
* simplifies tree traversal a lot |
| 331 |
|
| 332 |
* simplifies many XML algorithms |
| 333 |
|
| 334 |
|
| 335 |
Attributes in ElementTree |
| 336 |
========================= |
| 337 |
|
| 338 |
* uses ``.get()`` and ``.set()`` methods: |
| 339 |
|
| 340 |
.. sourcecode:: pycon |
| 341 |
|
| 342 |
>>> root = etree.fromstring( |
| 343 |
... '<root a="the value" b="of an" c="attribute"/>') |
| 344 |
|
| 345 |
>>> root.get('a') |
| 346 |
'the value' |
| 347 |
|
| 348 |
>>> root.set('a', "THE value") |
| 349 |
>>> root.get('a') |
| 350 |
'THE value' |
| 351 |
|
| 352 |
* or the ``.attrib`` dictionary property: |
| 353 |
|
| 354 |
.. sourcecode:: pycon |
| 355 |
|
| 356 |
>>> d = root.attrib |
| 357 |
|
| 358 |
>>> list(sorted(d.keys())) |
| 359 |
['a', 'b', 'c'] |
| 360 |
>>> list(sorted(d.values())) |
| 361 |
['THE value', 'attribute', 'of an'] |
| 362 |
|
| 363 |
|
| 364 |
Tree iteration in lxml.etree (1) |
| 365 |
================================ |
| 366 |
|
| 367 |
.. |
| 368 |
>>> import collections |
| 369 |
|
| 370 |
.. sourcecode:: pycon |
| 371 |
|
| 372 |
>>> root = etree.fromstring( |
| 373 |
... "<root> <a><b/><b/></a> <c><d/><e><f/></e><g/></c> </root>") |
| 374 |
|
| 375 |
>>> print([child.tag for child in root]) # children |
| 376 |
['a', 'c'] |
| 377 |
|
| 378 |
>>> print([el.tag for el in root.iter()]) # self and descendants |
| 379 |
['root', 'a', 'b', 'b', 'c', 'd', 'e', 'f', 'g'] |
| 380 |
|
| 381 |
>>> print([el.tag for el in root.iterdescendants()]) |
| 382 |
['a', 'b', 'b', 'c', 'd', 'e', 'f', 'g'] |
| 383 |
|
| 384 |
|
| 385 |
>>> def iter_breadth_first(root): |
| 386 |
... bfs_queue = collections.deque([root]) |
| 387 |
... while bfs_queue: |
| 388 |
... el = bfs_queue.popleft() # pop next element |
| 389 |
... bfs_queue.extend(el) # append its children |
| 390 |
... yield el |
| 391 |
|
| 392 |
>>> print([el.tag for el in iter_breadth_first(root)]) |
| 393 |
['root', 'a', 'c', 'b', 'b', 'd', 'e', 'g', 'f'] |
| 394 |
|
| 395 |
|
| 396 |
Tree iteration in lxml.etree (2) |
| 397 |
================================ |
| 398 |
|
| 399 |
.. sourcecode:: pycon |
| 400 |
|
| 401 |
>>> root = etree.fromstring( |
| 402 |
... "<root> <a><b/><b/></a> <c><d/><e><f/></e><g/></c> </root>") |
| 403 |
|
| 404 |
>>> tree_walker = etree.iterwalk(root, events=('start', 'end')) |
| 405 |
|
| 406 |
>>> for (event, element) in tree_walker: |
| 407 |
... print("%s (%s)" % (element.tag, event)) |
| 408 |
root (start) |
| 409 |
a (start) |
| 410 |
b (start) |
| 411 |
b (end) |
| 412 |
b (start) |
| 413 |
b (end) |
| 414 |
a (end) |
| 415 |
c (start) |
| 416 |
d (start) |
| 417 |
d (end) |
| 418 |
e (start) |
| 419 |
f (start) |
| 420 |
f (end) |
| 421 |
e (end) |
| 422 |
g (start) |
| 423 |
g (end) |
| 424 |
c (end) |
| 425 |
root (end) |
| 426 |
|
| 427 |
|
| 428 |
Path languages in lxml |
| 429 |
====================== |
| 430 |
|
| 431 |
.. sourcecode:: xml |
| 432 |
|
| 433 |
<root> |
| 434 |
<speech class='dialog'><p>So be it!</p></speech> |
| 435 |
<p>stuff</p> |
| 436 |
</root> |
| 437 |
|
| 438 |
* search it with XPath |
| 439 |
|
| 440 |
.. sourcecode:: pycon |
| 441 |
|
| 442 |
>>> find_paragraphs = etree.XPath("//p") |
| 443 |
>>> paragraphs = find_paragraphs(xml_tree) |
| 444 |
|
| 445 |
>>> print([ p.text for p in paragraphs ]) |
| 446 |
['So be it!', 'stuff'] |
| 447 |
|
| 448 |
* search it with CSS selectors |
| 449 |
|
| 450 |
.. sourcecode:: pycon |
| 451 |
|
| 452 |
>>> find_dialogs = cssselect.CSSSelector("speech.dialog p") |
| 453 |
>>> paragraphs = find_dialogs(xml_tree) |
| 454 |
|
| 455 |
>>> print([ p.text for p in paragraphs ]) |
| 456 |
['So be it!'] |
| 457 |
|
| 458 |
|
| 459 |
Summary of lesson 0 |
| 460 |
=================== |
| 461 |
|
| 462 |
* lxml comes with various tools |
| 463 |
|
| 464 |
* that aim to hide the quirks of XML |
| 465 |
|
| 466 |
* that simplify finding and handling data |
| 467 |
|
| 468 |
* that make XML a pythonic tool by itself |
| 469 |
|
| 470 |
|
| 471 |
Lesson 1: parsing XML/HTML |
| 472 |
========================== |
| 473 |
|
| 474 |
**The input side** |
| 475 |
|
| 476 |
(a quick overview) |
| 477 |
|
| 478 |
|
| 479 |
Parsing XML and HTML from ... |
| 480 |
============================= |
| 481 |
|
| 482 |
* strings: ``fromstring(xml_data)`` |
| 483 |
|
| 484 |
* byte strings, but also unicode strings |
| 485 |
|
| 486 |
* filenames: ``parse(filename)`` |
| 487 |
|
| 488 |
* HTTP/FTP URLs: ``parse(url)`` |
| 489 |
|
| 490 |
* file objects: ``parse(f)`` |
| 491 |
|
| 492 |
* ``f = open(filename, 'rb')`` ! |
| 493 |
|
| 494 |
* file-like objects: ``parse(f)`` |
| 495 |
|
| 496 |
* only need a ``f.read(size)`` method |
| 497 |
|
| 498 |
* data chunks: ``parser.feed(xml_chunk)`` |
| 499 |
|
| 500 |
* ``result = parser.close()`` |
| 501 |
|
| 502 |
.. class:: small right |
| 503 |
|
| 504 |
(parsing from strings and filenames/URLs frees the GIL) |
| 505 |
|
| 506 |
|
| 507 |
Example: parsing from a string |
| 508 |
============================== |
| 509 |
|
| 510 |
* using the ``fromstring()`` function: |
| 511 |
|
| 512 |
.. sourcecode:: pycon |
| 513 |
|
| 514 |
>>> root_element = etree.fromstring(some_xml_data) |
| 515 |
|
| 516 |
* using the ``fromstring()`` function with a specific parser: |
| 517 |
|
| 518 |
.. sourcecode:: pycon |
| 519 |
|
| 520 |
>>> parser = etree.HTMLParser(remove_comments=True) |
| 521 |
>>> root_element = etree.fromstring(some_html_data, parser) |
| 522 |
|
| 523 |
* or the ``XML()`` and ``HTML()`` aliases for literals in code: |
| 524 |
|
| 525 |
.. sourcecode:: pycon |
| 526 |
|
| 527 |
>>> root_element = etree.XML("<root><child/></root>") |
| 528 |
>>> root_element = etree.HTML("<p>some<br>paragraph</p>") |
| 529 |
|
| 530 |
|
| 531 |
Parsing XML into ... |
| 532 |
==================== |
| 533 |
|
| 534 |
* a tree in memory |
| 535 |
|
| 536 |
* ``parse()`` and ``fromstring()`` functions |
| 537 |
|
| 538 |
* a tree in memory, but step-by-step with a generator |
| 539 |
|
| 540 |
* ``iterparse()`` generates ``(start/end, element)`` events |
| 541 |
|
| 542 |
* tree can be cleaned up to save space |
| 543 |
|
| 544 |
* SAX-like callbacks without building a tree |
| 545 |
|
| 546 |
* ``parse()`` and ``fromstring()`` functions |
| 547 |
|
| 548 |
* pass a ``target`` object into the parser |
| 549 |
|
| 550 |
|
| 551 |
Summary of lesson 1 |
| 552 |
=================== |
| 553 |
|
| 554 |
* parsing XML/HTML in lxml is mostly straightforward |
| 555 |
|
| 556 |
* simple functions that do the job |
| 557 |
|
| 558 |
* advanced use cases are pretty simple |
| 559 |
|
| 560 |
* event-driven parsing using ``iterparse()`` |
| 561 |
|
| 562 |
* special parser configuration with keyword arguments |
| 563 |
|
| 564 |
* configuration is generally local to a parser |
| 565 |
|
| 566 |
* BTW: parsing is *very* fast, as is serialising |
| 567 |
|
| 568 |
* don't hesitate to do parse-serialise-parse cycles |
| 569 |
|
| 570 |
|
| 571 |
Lesson 2: generating XML |
| 572 |
======================== |
| 573 |
|
| 574 |
**The output side** |
| 575 |
|
| 576 |
(and how to make it safe and simple) |
| 577 |
|
| 578 |
|
| 579 |
The example language: Atom |
| 580 |
========================== |
| 581 |
|
| 582 |
The Atom XML format |
| 583 |
|
| 584 |
* Namespace: http://www.w3.org/2005/Atom |
| 585 |
|
| 586 |
* W3C recommendation derived from RSS and friends |
| 587 |
|
| 588 |
* Atom feeds describe news entries and annotated links |
| 589 |
|
| 590 |
* a ``feed`` contains one or more ``entry`` elements |
| 591 |
|
| 592 |
* an ``entry`` contains ``author``, ``link``, ``summary`` and/or ``content`` |
| 593 |
|
| 594 |
|
| 595 |
Example: generate XML (1) |
| 596 |
========================= |
| 597 |
|
| 598 |
The ElementMaker (or *E-factory*) |
| 599 |
|
| 600 |
.. sourcecode:: pycon |
| 601 |
|
| 602 |
>>> from lxml.builder import ElementMaker |
| 603 |
>>> A = ElementMaker(namespace="http://www.w3.org/2005/Atom", |
| 604 |
... nsmap={None : "http://www.w3.org/2005/Atom"}) |
| 605 |
|
| 606 |
.. class:: incremental |
| 607 |
|
| 608 |
.. sourcecode:: pycon |
| 609 |
|
| 610 |
>>> atom = A.feed( |
| 611 |
... A.author( A.name("Stefan Behnel") ), |
| 612 |
... A.entry( |
| 613 |
... A.title("News from lxml"), |
| 614 |
... A.link(href="http://codespeak.net/lxml/"), |
| 615 |
... A.summary("See what's <b>fun</b> about lxml...", |
| 616 |
... type="html"), |
| 617 |
... ) |
| 618 |
... ) |
| 619 |
|
| 620 |
.. sourcecode:: pycon |
| 621 |
|
| 622 |
>>> from lxml.etree import tostring |
| 623 |
>>> print( tostring(atom, pretty_print=True) ) |
| 624 |
|
| 625 |
|
| 626 |
Example: generate XML (2) |
| 627 |
========================= |
| 628 |
|
| 629 |
.. sourcecode:: pycon |
| 630 |
|
| 631 |
>>> atom = A.feed( |
| 632 |
... A.author( A.name("Stefan Behnel") ), |
| 633 |
... A.entry( |
| 634 |
... A.title("News from lxml"), |
| 635 |
... A.link(href="http://codespeak.net/lxml/"), |
| 636 |
... A.summary("See what's <b>fun</b> about lxml...", |
| 637 |
... type="html"), |
| 638 |
... ) |
| 639 |
... ) |
| 640 |
|
| 641 |
.. sourcecode:: xml |
| 642 |
|
| 643 |
<feed xmlns="http://www.w3.org/2005/Atom"> |
| 644 |
<author> |
| 645 |
<name>Stefan Behnel</name> |
| 646 |
</author> |
| 647 |
<entry> |
| 648 |
<title>News from lxml</title> |
| 649 |
<link href="http://codespeak.net/lxml/"/> |
| 650 |
<summary type="html">See what's <b>fun</b> |
| 651 |
about lxml...</summary> |
| 652 |
</entry> |
| 653 |
</feed> |
| 654 |
|
| 655 |
|
| 656 |
Be careful what you type! |
| 657 |
========================= |
| 658 |
|
| 659 |
.. sourcecode:: pycon |
| 660 |
|
| 661 |
>>> atom = A.feed( |
| 662 |
... A.author( A.name("Stefan Behnel") ), |
| 663 |
... A.entry( |
| 664 |
... A.titel("News from lxml"), |
| 665 |
... A.link(href="http://codespeak.net/lxml/"), |
| 666 |
... A.summary("See what's <b>fun</b> about lxml...", |
| 667 |
... type="html"), |
| 668 |
... ) |
| 669 |
... ) |
| 670 |
|
| 671 |
.. sourcecode:: xml |
| 672 |
|
| 673 |
<feed xmlns="http://www.w3.org/2005/Atom"> |
| 674 |
<author> |
| 675 |
<name>Stefan Behnel</name> |
| 676 |
</author> |
| 677 |
<entry> |
| 678 |
<titel>News from lxml</titel> |
| 679 |
<link href="http://codespeak.net/lxml/"/> |
| 680 |
<summary type="html">See what's <b>fun</b> |
| 681 |
about lxml...</summary> |
| 682 |
</entry> |
| 683 |
</feed> |
| 684 |
|
| 685 |
|
| 686 |
Want more 'type safety'? |
| 687 |
======================== |
| 688 |
|
| 689 |
Write an XML generator *module* instead: |
| 690 |
|
| 691 |
.. sourcecode:: python |
| 692 |
|
| 693 |
# atomgen.py |
| 694 |
|
| 695 |
from lxml import etree |
| 696 |
from lxml.builder import ElementMaker |
| 697 |
|
| 698 |
ATOM_NAMESPACE = "http://www.w3.org/2005/Atom" |
| 699 |
|
| 700 |
A = ElementMaker(namespace=ATOM_NAMESPACE, |
| 701 |
nsmap={None : ATOM_NAMESPACE}) |
| 702 |
|
| 703 |
feed = A.feed |
| 704 |
entry = A.entry |
| 705 |
title = A.title |
| 706 |
# ... and so on and so forth ... |
| 707 |
|
| 708 |
|
| 709 |
# plus a little validation function: isvalid() |
| 710 |
isvalid = etree.RelaxNG(file="atom.rng") |
| 711 |
|
| 712 |
|
| 713 |
The Atom generator module |
| 714 |
========================= |
| 715 |
|
| 716 |
.. |
| 717 |
>>> import sys |
| 718 |
>>> sys.path.insert(0, "ep2008") |
| 719 |
|
| 720 |
.. sourcecode:: pycon |
| 721 |
|
| 722 |
>>> import atomgen as A |
| 723 |
|
| 724 |
>>> atom = A.feed( |
| 725 |
... A.author( A.name("Stefan Behnel") ), |
| 726 |
... A.entry( |
| 727 |
... A.link(href="http://codespeak.net/lxml/"), |
| 728 |
... A.title("News from lxml"), |
| 729 |
... A.summary("See what's <b>fun</b> about lxml...", |
| 730 |
... type="html"), |
| 731 |
... ) |
| 732 |
... ) |
| 733 |
|
| 734 |
>>> A.isvalid(atom) # ok, forgot the ID's => invalid XML ... |
| 735 |
False |
| 736 |
|
| 737 |
>>> title = A.titel("News from lxml") |
| 738 |
Traceback (most recent call last): |
| 739 |
... |
| 740 |
AttributeError: 'module' object has no attribute 'titel' |
| 741 |
|
| 742 |
|
| 743 |
Mixing languages (1) |
| 744 |
==================== |
| 745 |
|
| 746 |
Atom can embed *serialised* HTML |
| 747 |
|
| 748 |
.. sourcecode:: pycon |
| 749 |
|
| 750 |
>>> import lxml.html.builder as h |
| 751 |
|
| 752 |
>>> html_fragment = h.DIV( |
| 753 |
... "this is some\n", |
| 754 |
... h.A("HTML", href="http://w3.org/MarkUp/"), |
| 755 |
... "\ncontent") |
| 756 |
|
| 757 |
.. class:: incremental |
| 758 |
|
| 759 |
.. sourcecode:: pycon |
| 760 |
|
| 761 |
>>> serialised_html = etree.tostring(html_fragment, method="html") |
| 762 |
|
| 763 |
>>> summary = A.summary(serialised_html, type="html") |
| 764 |
|
| 765 |
.. sourcecode:: pycon |
| 766 |
|
| 767 |
>>> print(etree.tostring(summary)) |
| 768 |
<summary xmlns="http://www.w3.org/2005/Atom" type="html"> |
| 769 |
<div>this is some |
| 770 |
<a href="http://w3.org/MarkUp/">HTML</a> |
| 771 |
content</div> |
| 772 |
</summary> |
| 773 |
|
| 774 |
|
| 775 |
Mixing languages (2) |
| 776 |
==================== |
| 777 |
|
| 778 |
Atom can also embed non-escaped XHTML |
| 779 |
|
| 780 |
.. sourcecode:: pycon |
| 781 |
|
| 782 |
>>> from copy import deepcopy |
| 783 |
>>> xhtml_fragment = deepcopy(html_fragment) |
| 784 |
|
| 785 |
>>> from lxml.html import html_to_xhtml |
| 786 |
>>> html_to_xhtml(xhtml_fragment) |
| 787 |
|
| 788 |
>>> summary = A.summary(xhtml_fragment, type="xhtml") |
| 789 |
|
| 790 |
.. class:: incremental |
| 791 |
|
| 792 |
.. sourcecode:: pycon |
| 793 |
|
| 794 |
>>> print(etree.tostring(summary, pretty_print=True)) |
| 795 |
<summary xmlns="http://www.w3.org/2005/Atom" type="xhtml"> |
| 796 |
<html:div xmlns:html="http://www.w3.org/1999/xhtml">this is some |
| 797 |
<html:a href="http://w3.org/MarkUp/">HTML</html:a> |
| 798 |
content</html:div> |
| 799 |
</summary> |
| 800 |
|
| 801 |
|
| 802 |
Summary of lesson 2 |
| 803 |
=================== |
| 804 |
|
| 805 |
* generating XML is easy |
| 806 |
|
| 807 |
* use the ElementMaker |
| 808 |
|
| 809 |
* wrap it in a module that provides |
| 810 |
|
| 811 |
* the target namespace |
| 812 |
|
| 813 |
* an ElementMaker name for each language element |
| 814 |
|
| 815 |
* a validator |
| 816 |
|
| 817 |
* maybe additional helper functions |
| 818 |
|
| 819 |
* mixing languages is easy |
| 820 |
|
| 821 |
* define a generator module for each |
| 822 |
|
| 823 |
\... this is all you need for the *output* side of XML languages |
| 824 |
|
| 825 |
|
| 826 |
Lesson 3: Designing XML APIs |
| 827 |
============================ |
| 828 |
|
| 829 |
**The Element API** |
| 830 |
|
| 831 |
(and how to make it the way *you* want) |
| 832 |
|
| 833 |
|
| 834 |
Trees in C and in Python |
| 835 |
======================== |
| 836 |
|
| 837 |
* Trees have two representations: |
| 838 |
|
| 839 |
* a plain, complete, low-level C tree provided by libxml2 |
| 840 |
|
| 841 |
* a set of Python Element proxies, each representing one element |
| 842 |
|
| 843 |
* Proxies are created on-the-fly: |
| 844 |
|
| 845 |
* lxml creates an Element object for a C node on request |
| 846 |
|
| 847 |
* proxies are garbage collected when going out of scope |
| 848 |
|
| 849 |
* XML trees are garbage collected when deleting the last proxy |
| 850 |
|
| 851 |
.. class:: center |
| 852 |
|
| 853 |
.. image:: ep2008/proxies.png |
| 854 |
|
| 855 |
|
| 856 |
Mapping Python classes to nodes |
| 857 |
=============================== |
| 858 |
|
| 859 |
* Proxies can be assigned to XML nodes *by user code* |
| 860 |
|
| 861 |
* lxml tells you about a node, you return a class |
| 862 |
|
| 863 |
|
| 864 |
Example: a simple Element class (1) |
| 865 |
=================================== |
| 866 |
|
| 867 |
* define a subclass of ElementBase |
| 868 |
|
| 869 |
.. sourcecode:: pycon |
| 870 |
|
| 871 |
>>> class HonkElement(etree.ElementBase): |
| 872 |
... @property |
| 873 |
... def honking(self): |
| 874 |
... return self.get('honking') == 'true' |
| 875 |
|
| 876 |
* let it replace the default Element class |
| 877 |
|
| 878 |
.. sourcecode:: pycon |
| 879 |
|
| 880 |
>>> lookup = etree.ElementDefaultClassLookup( |
| 881 |
... element=HonkElement) |
| 882 |
|
| 883 |
>>> parser = etree.XMLParser() |
| 884 |
>>> parser.set_element_class_lookup(lookup) |
| 885 |
|
| 886 |
|
| 887 |
Example: a simple Element class (2) |
| 888 |
=================================== |
| 889 |
|
| 890 |
* use the new Element class |
| 891 |
|
| 892 |
.. sourcecode:: pycon |
| 893 |
|
| 894 |
>>> root = etree.XML('<root><honk honking="true"/></root>', |
| 895 |
... parser) |
| 896 |
|
| 897 |
>>> root.honking |
| 898 |
False |
| 899 |
>>> root[0].honking |
| 900 |
True |
| 901 |
|
| 902 |
|
| 903 |
Mapping Python classes to nodes |
| 904 |
=============================== |
| 905 |
|
| 906 |
* The Element class lookup |
| 907 |
|
| 908 |
* lxml tells you about a node, you return a class |
| 909 |
|
| 910 |
* no restrictions on lookup algorithm |
| 911 |
|
| 912 |
* each parser can use a different class lookup scheme |
| 913 |
|
| 914 |
* lookup schemes can be chained through fallbacks |
| 915 |
|
| 916 |
* Classes can be selected based on |
| 917 |
|
| 918 |
* the node type (element, comment or processing instruction) |
| 919 |
|
| 920 |
* ``ElementDefaultClassLookup()`` |
| 921 |
|
| 922 |
* the namespaced node name |
| 923 |
|
| 924 |
* ``CustomElementClassLookup()`` + a fallback |
| 925 |
|
| 926 |
* ``ElementNamespaceClassLookup()`` + a fallback |
| 927 |
|
| 928 |
* the value of an attribute (e.g. ``id`` or ``class``) |
| 929 |
|
| 930 |
* ``AttributeBasedElementClassLookup()`` + a fallback |
| 931 |
|
| 932 |
* read-only inspection of the tree |
| 933 |
|
| 934 |
* ``PythonElementClassLookup()`` + a fallback |
| 935 |
|
| 936 |
|
| 937 |
Designing an Atom API |
| 938 |
===================== |
| 939 |
|
| 940 |
* a feed is a container for entries |
| 941 |
|
| 942 |
.. sourcecode:: python |
| 943 |
|
| 944 |
# atom.py |
| 945 |
|
| 946 |
ATOM_NAMESPACE = "http://www.w3.org/2005/Atom" |
| 947 |
_ATOM_NS = "{%s}" % ATOM_NAMESPACE |
| 948 |
|
| 949 |
class FeedElement(etree.ElementBase): |
| 950 |
@property |
| 951 |
def entries(self): |
| 952 |
return self.findall(_ATOM_NS + "entry") |
| 953 |
|
| 954 |
* it also has a couple of meta-data children, e.g. ``title`` |
| 955 |
|
| 956 |
.. sourcecode:: python |
| 957 |
|
| 958 |
class FeedElement(etree.ElementBase): |
| 959 |
# ... |
| 960 |
@property |
| 961 |
def title(self): |
| 962 |
"return the title or None" |
| 963 |
return self.find("title") |
| 964 |
|
| 965 |
|
| 966 |
Consider lxml.objectify |
| 967 |
======================= |
| 968 |
|
| 969 |
* ready-to-use, generic Python object API for XML |
| 970 |
|
| 971 |
.. sourcecode:: python |
| 972 |
|
| 973 |
>>> from lxml import objectify |
| 974 |
|
| 975 |
>>> feed = objectify.parse("atom-example.xml") |
| 976 |
>>> print(feed.title) |
| 977 |
Example Feed |
| 978 |
|
| 979 |
>>> print([entry.title for entry in feed.entry]) |
| 980 |
['Atom-Powered Robots Run Amok'] |
| 981 |
|
| 982 |
>>> print(feed.entry[0].title) |
| 983 |
Atom-Powered Robots Run Amok |
| 984 |
|
| 985 |
|
| 986 |
Still room for more convenience |
| 987 |
=============================== |
| 988 |
|
| 989 |
.. sourcecode:: python |
| 990 |
|
| 991 |
from itertools import chain |
| 992 |
|
| 993 |
class FeedElement(objectify.ObjectifiedElement): |
| 994 |
|
| 995 |
def addIDs(self): |
| 996 |
"initialise the IDs of feed and entries" |
| 997 |
|
| 998 |
for element in chain([self], self.entry): |
| 999 |
if element.find(_ATOM_NS + "id") is None: |
| 1000 |
id = etree.SubElement(self, _ATOM_NS + "id") |
| 1001 |
id.text = make_guid() |
| 1002 |
|
| 1003 |
|
| 1004 |
Incremental API design |
| 1005 |
====================== |
| 1006 |
|
| 1007 |
* choose an XML API to start with |
| 1008 |
|
| 1009 |
* lxml.etree is general purpose |
| 1010 |
|
| 1011 |
* lxml.objectify is nice for document-style XML |
| 1012 |
|
| 1013 |
* fix Elements that really need some API sugar |
| 1014 |
|
| 1015 |
* dict-mappings to children with specific content/attributes |
| 1016 |
|
| 1017 |
* properties for specially typed attributes or child values |
| 1018 |
|
| 1019 |
* simplified access to varying content types of an element |
| 1020 |
|
| 1021 |
* shortcuts for unnecessarily deep subtrees |
| 1022 |
|
| 1023 |
* ignore what works well enough with the Element API |
| 1024 |
|
| 1025 |
* lists of homogeneous children -> Element iteration |
| 1026 |
|
| 1027 |
* string attributes -> .get()/.set() |
| 1028 |
|
| 1029 |
* let the API grow at your fingertips |
| 1030 |
|
| 1031 |
* play with it and test use cases |
| 1032 |
|
| 1033 |
* avoid "I want because I can" feature explosion! |
| 1034 |
|
| 1035 |
|
| 1036 |
Setting up the Element mapping |
| 1037 |
============================== |
| 1038 |
|
| 1039 |
Atom has a namespace => leave the mapping to lxml |
| 1040 |
|
| 1041 |
.. sourcecode:: python |
| 1042 |
|
| 1043 |
# ... |
| 1044 |
_atom_lookup = etree.ElementNamespaceClassLookup( |
| 1045 |
objectify.ObjectifyElementClassLookup()) |
| 1046 |
|
| 1047 |
# map the classes to tag names |
| 1048 |
ns = _atom_lookup.get_namespace(ATOM_NAMESPACE) |
| 1049 |
ns["feed"] = FeedElement |
| 1050 |
ns["entry"] = EntryElement |
| 1051 |
# ... and so on |
| 1052 |
# or use ns.update(vars()) with appropriate class names |
| 1053 |
|
| 1054 |
# create a parser that does some whitespace cleanup |
| 1055 |
atom_parser = etree.XMLParser(remove_blank_text=True) |
| 1056 |
|
| 1057 |
# make it use our Atom classes |
| 1058 |
atom_parser.set_element_class_lookup(_atom_lookup) |
| 1059 |
|
| 1060 |
# and help users in using our parser setup |
| 1061 |
def parse(input): |
| 1062 |
return etree.parse(input, atom_parser) |
| 1063 |
|
| 1064 |
|
| 1065 |
Using your new Atom API |
| 1066 |
======================= |
| 1067 |
|
| 1068 |
.. sourcecode:: pycon |
| 1069 |
|
| 1070 |
>>> import atom |
| 1071 |
>>> feed = atom.parse("ep2008/atom-example.xml").getroot() |
| 1072 |
|
| 1073 |
>>> print(len(feed.entry)) |
| 1074 |
1 |
| 1075 |
>>> print([entry.title for entry in feed.entry]) |
| 1076 |
['Atom-Powered Robots Run Amok'] |
| 1077 |
|
| 1078 |
>>> link_tag = "{%s}link" % atom.ATOM_NAMESPACE |
| 1079 |
>>> print([link.get("href") for link in feed.iter(link_tag)]) |
| 1080 |
['http://example.org/', 'http://example.org/2003/12/13/atom03'] |
| 1081 |
|
| 1082 |
|
| 1083 |
Summary of lesson 3 |
| 1084 |
=================== |
| 1085 |
|
| 1086 |
To implement an XML API ... |
| 1087 |
|
| 1088 |
1) start off with lxml's Element API |
| 1089 |
|
| 1090 |
* or take a look at the object API of lxml.objectify |
| 1091 |
|
| 1092 |
2) specialise it into a set of custom Element classes |
| 1093 |
|
| 1094 |
3) map them to XML tags using one of the lookup schemes |
| 1095 |
|
| 1096 |
4) improve the API incrementally while using it |
| 1097 |
|
| 1098 |
* discover inconveniences and beautify them |
| 1099 |
|
| 1100 |
* avoid putting work into things that work |
| 1101 |
|
| 1102 |
|
| 1103 |
Conclusion |
| 1104 |
========== |
| 1105 |
|
| 1106 |
lxml ... |
| 1107 |
|
| 1108 |
* provides a convenient set of tools for XML and HTML |
| 1109 |
|
| 1110 |
* parsing |
| 1111 |
|
| 1112 |
* generating |
| 1113 |
|
| 1114 |
* working with in-memory trees |
| 1115 |
|
| 1116 |
* follows Python idioms wherever possible |
| 1117 |
|
| 1118 |
* highly extensible through wrapping and subclassing |
| 1119 |
|
| 1120 |
* callable objects for XPath, CSS selectors, XSLT, schemas |
| 1121 |
|
| 1122 |
* iteration for tree traversal (even while parsing) |
| 1123 |
|
| 1124 |
* list-/dict-like APIs, properties, keyword arguments, ... |
| 1125 |
|
| 1126 |
* makes extension and specialisation easy |
| 1127 |
|
| 1128 |
* write a special XML generator module in trivial code |
| 1129 |
|
| 1130 |
* write your own XML API incrementally on-the-fly |