Debian Codegraph @

doc/element_classes.txt

raw
1 ====================================
2 Using custom Element classes in lxml
3 ====================================
4
5 lxml has very sophisticated support for custom Element classes. You
6 can provide your own classes for Elements and have lxml use them by
7 default for all elements generated by a specific parser, only for a
8 specific tag name in a specific namespace or even for an exact element
9 at a specific position in the tree.
10
11 Custom Elements must inherit from the ``lxml.etree.ElementBase`` class, which
12 provides the Element interface for subclasses:
13
14 .. sourcecode:: pycon
15
16 >>> from lxml import etree
17
18 >>> class honk(etree.ElementBase):
19 ... @property
20 ... def honking(self):
21 ... return self.get('honking') == 'true'
22
23 This defines a new Element class ``honk`` with a property ``honking``.
24
25 The following document describes how you can make lxml.etree use these
26 custom Element classes.
27
28 .. contents::
29 ..
30 1 Background on Element proxies
31 2 Element initialization
32 3 Setting up a class lookup scheme
33 3.1 Default class lookup
34 3.2 Namespace class lookup
35 3.3 Attribute based lookup
36 3.4 Custom element class lookup
37 3.5 Tree based element class lookup in Python
38 4 Generating XML with custom classes
39 5 Implementing namespaces
40
41
42 Background on Element proxies
43 =============================
44
45 Being based on libxml2, lxml.etree holds the entire XML tree in a C
46 structure. To communicate with Python code, it creates Python proxy
47 objects for the XML elements on demand.
48
49 .. image:: proxies.png
50
51 The mapping between C elements and Python Element classes is
52 completely configurable. When you ask lxml.etree for an Element by
53 using its API, it will instantiate your classes for you. All you have
54 to do is tell lxml which class to use for which kind of Element. This
55 is done through a class lookup scheme, as described in the sections
56 below.
57
58
59 Element initialization
60 ======================
61
62 There is one thing to know up front. Element classes *must not* have
63 an ``__init__`` or ``__new__`` method. There should not be any
64 internal state either, except for the data stored in the underlying
65 XML tree. Element instances are created and garbage collected at
66 need, so there is normally no way to predict when and how often a
67 proxy is created for them. Even worse, when the ``__init__`` method
68 is called, the object is not even initialized yet to represent the XML
69 tag, so there is not much use in providing an ``__init__`` method in
70 subclasses.
71
72 Most use cases will not require any class initialisation or proxy
73 state, so you can content yourself with skipping to the next section
74 for now. However, if you really need to set up your element class on
75 instantiation, or need a way to persistently store state in the proxy
76 instances instead of the XML tree, here is a way to do so.
77
78 There is one important guarantee regarding Element proxies. Once a
79 proxy has been instantiated, it will keep alive as long as there is a
80 Python reference to it, and any access to the XML element in the tree
81 will return this very instance. Therefore, if you need to store local
82 state in a custom Element class (which is generally discouraged), you
83 can do so by keeping the Elements in a tree alive. If the tree
84 doesn't change, you can simply do this:
85
86 .. sourcecode:: python
87
88 proxy_cache = list(root.iter())
89
90 or
91
92 .. sourcecode:: python
93
94 proxy_cache = set(root.iter())
95
96 or use any other suitable container. Note that you have to keep this
97 cache manually up to date if the tree changes, which can get tricky in
98 cases.
99
100 For proxy initialisation, ElementBase classes have an ``_init()``
101 method that can be overridden, as opposed to the normal ``__init__()``
102 method. It can be used to modify the XML tree, e.g. to construct
103 special children or verify and update attributes.
104
105 The semantics of ``_init()`` are as follows:
106
107 * It is called once on Element class instantiation time. That is,
108 when a Python representation of the element is created by lxml. At
109 that time, the element object is completely initialized to represent
110 a specific XML element within the tree.
111
112 * The method has complete access to the XML tree. Modifications can be done
113 in exactly the same way as anywhere else in the program.
114
115 * Python representations of elements may be created multiple times during the
116 lifetime of an XML element in the underlying C tree. The ``_init()`` code
117 provided by subclasses must take special care by itself that multiple
118 executions either are harmless or that they are prevented by some kind of
119 flag in the XML tree. The latter can be achieved by modifying an attribute
120 value or by removing or adding a specific child node and then verifying this
121 before running through the init process.
122
123 * Any exceptions raised in ``_init()`` will be propagated through the API
124 call that led to the creation of the Element. So be careful with the code
125 you write here as its exceptions may turn up in various unexpected places.
126
127
128 Setting up a class lookup scheme
129 ================================
130
131 The first thing to do when deploying custom element classes is to register a
132 class lookup scheme on a parser. lxml.etree provides quite a number of
133 different schemes that also support class lookup based on namespaces or
134 attribute values. Most lookups support fallback chaining, which allows the
135 next lookup mechanism to take over when the previous one fails to find a
136 class.
137
138 For example, setting the ``honk`` Element as a default element class
139 for a parser works as follows:
140
141 .. sourcecode:: pycon
142
143 >>> parser_lookup = etree.ElementDefaultClassLookup(element=honk)
144 >>> parser = etree.XMLParser()
145 >>> parser.set_element_class_lookup(parser_lookup)
146
147 There is one drawback of the parser based scheme: the ``Element()`` factory
148 does not know about your specialised parser and creates a new document that
149 deploys the default parser:
150
151 .. sourcecode:: pycon
152
153 >>> el = etree.Element("root")
154 >>> print(isinstance(el, honk))
155 False
156
157 You should therefore avoid using this factory function in code that
158 uses custom classes. The ``makeelement()`` method of parsers provides
159 a simple replacement:
160
161 .. sourcecode:: pycon
162
163 >>> el = parser.makeelement("root")
164 >>> print(isinstance(el, honk))
165 True
166
167 If you use a parser at the module level, you can easily redirect a module
168 level ``Element()`` factory to the parser method by adding code like this:
169
170 .. sourcecode:: pycon
171
172 >>> module_level_parser = etree.XMLParser()
173 >>> Element = module_level_parser.makeelement
174
175 While the ``XML()`` and ``HTML()`` factories also depend on the default
176 parser, you can pass them a different parser as second argument:
177
178 .. sourcecode:: pycon
179
180 >>> element = etree.XML("<test/>")
181 >>> print(isinstance(element, honk))
182 False
183
184 >>> element = etree.XML("<test/>", parser)
185 >>> print(isinstance(element, honk))
186 True
187
188 Whenever you create a document with a parser, it will inherit the lookup
189 scheme and all subsequent element instantiations for this document will use
190 it:
191
192 .. sourcecode:: pycon
193
194 >>> element = etree.fromstring("<test/>", parser)
195 >>> print(isinstance(element, honk))
196 True
197 >>> el = etree.SubElement(element, "subel")
198 >>> print(isinstance(el, honk))
199 True
200
201 For testing code in the Python interpreter and for small projects, you
202 may also consider setting a lookup scheme on the default parser. To
203 avoid interfering with other modules, however, it is usually a better
204 idea to use a dedicated parser for each module (or a parser pool when
205 using threads) and then register the required lookup scheme only for
206 this parser.
207
208
209 Default class lookup
210 --------------------
211
212 This is the most simple lookup mechanism. It always returns the default
213 element class. Consequently, no further fallbacks are supported, but this
214 scheme is a nice fallback for other custom lookup mechanisms. Specifically,
215 it also handles comments and processing instructions, which are easy to
216 forget about when mapping proxies to classes.
217
218 Usage:
219
220 .. sourcecode:: pycon
221
222 >>> lookup = etree.ElementDefaultClassLookup()
223 >>> parser = etree.XMLParser()
224 >>> parser.set_element_class_lookup(lookup)
225
226 Note that the default for new parsers is to use the global fallback, which is
227 also the default lookup (if not configured otherwise).
228
229 To change the default element implementation, you can pass your new class to
230 the constructor. While it accepts classes for ``element``, ``comment`` and
231 ``pi`` nodes, most use cases will only override the element class:
232
233 .. sourcecode:: pycon
234
235 >>> el = parser.makeelement("myelement")
236 >>> print(isinstance(el, honk))
237 False
238
239 >>> lookup = etree.ElementDefaultClassLookup(element=honk)
240 >>> parser.set_element_class_lookup(lookup)
241
242 >>> el = parser.makeelement("myelement")
243 >>> print(isinstance(el, honk))
244 True
245 >>> el.honking
246 False
247 >>> el = parser.makeelement("myelement", honking='true')
248 >>> etree.tostring(el)
249 b'<myelement honking="true"/>'
250 >>> el.honking
251 True
252
253 >>> root = etree.fromstring(
254 ... '<root honking="true"><!--comment--></root>', parser)
255 >>> root.honking
256 True
257 >>> print(root[0].text)
258 comment
259
260
261 Namespace class lookup
262 ----------------------
263
264 This is an advanced lookup mechanism that supports namespace/tag-name specific
265 element classes. You can select it by calling:
266
267 .. sourcecode:: pycon
268
269 >>> lookup = etree.ElementNamespaceClassLookup()
270 >>> parser = etree.XMLParser()
271 >>> parser.set_element_class_lookup(lookup)
272
273 See the separate section on `implementing namespaces`_ below to learn how to
274 make use of it.
275
276 .. _`implementing namespaces`: #implementing-namespaces
277
278 This scheme supports a fallback mechanism that is used in the case where the
279 namespace is not found or no class was registered for the element name.
280 Normally, the default class lookup is used here. To change it, pass the
281 desired fallback lookup scheme to the constructor:
282
283 .. sourcecode:: pycon
284
285 >>> fallback = etree.ElementDefaultClassLookup(element=honk)
286 >>> lookup = etree.ElementNamespaceClassLookup(fallback)
287 >>> parser.set_element_class_lookup(lookup)
288
289 >>> root = etree.fromstring(
290 ... '<root honking="true"><!--comment--></root>', parser)
291 >>> root.honking
292 True
293 >>> print(root[0].text)
294 comment
295
296
297 Attribute based lookup
298 ----------------------
299
300 This scheme uses a mapping from attribute values to classes. An attribute
301 name is set at initialisation time and is then used to find the corresponding
302 value in a dictionary. It is set up as follows:
303
304 .. sourcecode:: pycon
305
306 >>> id_class_mapping = {'1234' : honk} # maps attribute values to classes
307
308 >>> lookup = etree.AttributeBasedElementClassLookup(
309 ... 'id', id_class_mapping)
310 >>> parser = etree.XMLParser()
311 >>> parser.set_element_class_lookup(lookup)
312
313 And here is how to use it:
314
315 .. sourcecode:: pycon
316
317 >>> xml = '<a id="123"><b id="1234"/><b id="1234" honking="true"/></a>'
318 >>> a = etree.fromstring(xml, parser)
319
320 >>> a.honking # id does not match !
321 Traceback (most recent call last):
322 AttributeError: 'lxml.etree._Element' object has no attribute 'honking'
323
324 >>> a[0].honking
325 False
326 >>> a[1].honking
327 True
328
329 This lookup scheme uses its fallback if the attribute is not found or
330 its value is not in the mapping. Normally, the default class lookup
331 is used here. If you want to use the namespace lookup, for example,
332 you can use this code:
333
334 .. sourcecode:: pycon
335
336 >>> fallback = etree.ElementNamespaceClassLookup()
337 >>> lookup = etree.AttributeBasedElementClassLookup(
338 ... 'id', id_class_mapping, fallback)
339 >>> parser = etree.XMLParser()
340 >>> parser.set_element_class_lookup(lookup)
341
342
343 Custom element class lookup
344 ---------------------------
345
346 This is the most customisable way of finding element classes on a per-element
347 basis. It allows you to implement a custom lookup scheme in a subclass:
348
349 .. sourcecode:: pycon
350
351 >>> class MyLookup(etree.CustomElementClassLookup):
352 ... def lookup(self, node_type, document, namespace, name):
353 ... if node_type == 'element':
354 ... return honk # be a bit more selective here ...
355 ... else:
356 ... return None # pass on to (default) fallback
357
358 >>> parser = etree.XMLParser()
359 >>> parser.set_element_class_lookup(MyLookup())
360
361 >>> root = etree.fromstring(
362 ... '<root honking="true"><!--comment--></root>', parser)
363 >>> root.honking
364 True
365 >>> print(root[0].text)
366 comment
367
368 The ``.lookup()`` method must return either None (which triggers the
369 fallback mechanism) or a subclass of ``lxml.etree.ElementBase``. It
370 can take any decision it wants based on the node type (one of
371 "element", "comment", "PI", "entity"), the XML document of the
372 element, or its namespace or tag name.
373
374
375 Tree based element class lookup in Python
376 -----------------------------------------
377
378 Taking more elaborate decisions than allowed by the custom scheme is
379 difficult to achieve in pure Python, as it results in a
380 chicken-and-egg problem. It would require access to the tree - before
381 the elements in the tree have been instantiated as Python Element
382 proxies.
383
384 Luckily, there is a way to do this. The ``PythonElementClassLookup``
385 works similarly to the custom lookup scheme:
386
387 .. sourcecode:: pycon
388
389 >>> class MyLookup(etree.PythonElementClassLookup):
390 ... def lookup(self, document, element):
391 ... return MyElementClass # defined elsewhere
392
393 >>> parser = etree.XMLParser()
394 >>> parser.set_element_class_lookup(MyLookup())
395
396 As before, the first argument to the ``lookup()`` method is the opaque
397 document instance that contains the Element. The second argument is a
398 lightweight Element proxy implementation that is only valid during the lookup.
399 Do not try to keep a reference to it. Once the lookup is finished, the proxy
400 will become invalid. You will get an ``AssertionError`` if you access any of
401 the properties or methods outside the scope of the lookup call where they were
402 instantiated.
403
404 During the lookup, the element object behaves mostly like a normal Element
405 instance. It provides the properties ``tag``, ``text``, ``tail`` etc. and
406 supports indexing, slicing and the ``getchildren()``, ``getparent()``
407 etc. methods. It does *not* support iteration, nor does it support any kind
408 of modification. All of its properties are read-only and it cannot be removed
409 or inserted into other trees. You can use it as a starting point to freely
410 traverse the tree and collect any kind of information that its elements
411 provide. Once you have taken the decision which class to use for this
412 element, you can simply return it and have lxml take care of cleaning up the
413 instantiated proxy classes.
414
415 Sidenote: this lookup scheme originally lived in a separate module called
416 ``lxml.pyclasslookup``.
417
418
419 Generating XML with custom classes
420 ==================================
421
422 Up to lxml 2.1, you could not instantiate proxy classes yourself.
423 Only lxml.etree could do that when creating an object representation
424 of an existing XML element. Since lxml 2.2, however, instantiating
425 this class will simply create a new Element:
426
427 .. sourcecode:: pycon
428
429 >>> el = honk(honking='true')
430 >>> el.tag
431 'honk'
432 >>> el.honking
433 True
434
435 Note, however, that the proxy you create here will be garbage
436 collected just like any other proxy. You can therefore not count on
437 lxml.etree using the same class that you instantiated when you access
438 this Element a second time after letting its reference go. You should
439 therefore always use a corresponding class lookup scheme that returns
440 your Element proxy classes for the elements that they create. The
441 ``ElementNamespaceClassLookup`` is generally a good match.
442
443 You can use custom Element classes to quickly create XML fragments:
444
445 .. sourcecode:: pycon
446
447 >>> class hale(etree.ElementBase): pass
448 >>> class bopp(etree.ElementBase): pass
449
450 >>> el = hale( "some ", honk(honking = 'true'), bopp, " text" )
451
452 >>> print(etree.tostring(el, encoding='unicode'))
453 <hale>some <honk honking="true"/><bopp/> text</hale>
454
455
456 Implementing namespaces
457 =======================
458
459 lxml allows you to implement namespaces, in a rather literal sense. After
460 setting up the namespace class lookup mechanism as described above, you can
461 build a new element namespace (or retrieve an existing one) by calling the
462 ``get_namespace(uri)`` method of the lookup:
463
464 .. sourcecode:: pycon
465
466 >>> lookup = etree.ElementNamespaceClassLookup()
467 >>> parser = etree.XMLParser()
468 >>> parser.set_element_class_lookup(lookup)
469
470 >>> namespace = lookup.get_namespace('http://hui.de/honk')
471
472 and then register the new element type with that namespace, say, under the tag
473 name ``honk``:
474
475 .. sourcecode:: pycon
476
477 >>> namespace['honk'] = honk
478
479 If you have many Element classes declared in one module, and they are
480 all named like the elements they create, you can simply use
481 ``namespace.update(globals())`` at the end of your module to declare them
482 automatically. The implementation is smart enough to ignore
483 everything that is not an Element class.
484
485 After this, you create and use your XML elements through the normal API of
486 lxml:
487
488 .. sourcecode:: pycon
489
490 >>> xml = '<honk xmlns="http://hui.de/honk" honking="true"/>'
491 >>> honk_element = etree.XML(xml, parser)
492 >>> print(honk_element.honking)
493 True
494
495 The same works when creating elements by hand:
496
497 .. sourcecode:: pycon
498
499 >>> honk_element = parser.makeelement('{http://hui.de/honk}honk',
500 ... honking='true')
501 >>> print(honk_element.honking)
502 True
503
504 Essentially, what this allows you to do, is to give Elements a custom API
505 based on their namespace and tag name.
506
507 A somewhat related topic are `extension functions`_ which use a similar
508 mechanism for registering Python functions for use in XPath and XSLT.
509
510 .. _`extension functions`: extensions.html
511
512 In the setup example above, we associated the ``honk`` Element class
513 only with the 'honk' element. If an XML tree contains different
514 elements in the same namespace, they do not pick up the same
515 implementation:
516
517 .. sourcecode:: pycon
518
519 >>> xml = ('<honk xmlns="http://hui.de/honk" honking="true">'
520 ... '<bla/><!--comment-->'
521 ... '</honk>')
522 >>> honk_element = etree.XML(xml, parser)
523 >>> print(honk_element.honking)
524 True
525 >>> print(honk_element[0].honking)
526 Traceback (most recent call last):
527 ...
528 AttributeError: 'lxml.etree._Element' object has no attribute 'honking'
529 >>> print(honk_element[1].text)
530 comment
531
532 You can therefore provide one implementation per element name in each
533 namespace and have lxml select the right one on the fly. If you want one
534 element implementation per namespace (ignoring the element name) or prefer
535 having a common class for most elements except a few, you can specify a
536 default implementation for an entire namespace by registering that class with
537 the empty element name (``None``).
538
539 You may consider following an object oriented approach here. If you build a
540 class hierarchy of element classes, you can also implement a base class for a
541 namespace that is used if no specific element class is provided. Again, you
542 can just pass None as an element name:
543
544 .. sourcecode:: pycon
545
546 >>> class HonkNSElement(etree.ElementBase):
547 ... def honk(self):
548 ... return "HONK"
549 >>> namespace[None] = HonkNSElement # default Element for namespace
550
551 >>> class HonkElement(HonkNSElement):
552 ... @property
553 ... def honking(self):
554 ... return self.get('honking') == 'true'
555 >>> namespace['honk'] = HonkElement # Element for specific tag
556
557 Now you can rely on lxml to always return objects of type HonkNSElement or its
558 subclasses for elements of this namespace:
559
560 .. sourcecode:: pycon
561
562 >>> xml = ('<honk xmlns="http://hui.de/honk" honking="true">'
563 ... '<bla/><!--comment-->'
564 ... '</honk>')
565 >>> honk_element = etree.fromstring(xml, parser)
566
567 >>> print(type(honk_element))
568 <class 'HonkElement'>
569 >>> print(type(honk_element[0]))
570 <class 'HonkNSElement'>
571
572 >>> print(honk_element.honking)
573 True
574 >>> print(honk_element.honk())
575 HONK
576
577 >>> print(honk_element[0].honk())
578 HONK
579 >>> print(honk_element[0].honking) # doctest: +ELLIPSIS
580 Traceback (most recent call last):
581 ...
582 AttributeError: 'HonkNSElement' object has no attribute 'honking'...
583
584 >>> print(honk_element[1].text) # uses fallback for non-elements
585 comment
586
587 Since lxml 4.1, the registration is more conveniently done with
588 class decorators. The namespace registry object is callable with
589 a name (or ``None``) as argument and can then be used as decorator.
590
591 .. sourcecode:: pycon
592
593 >>> honk_elements = lookup.get_namespace('http://hui.de/honk')
594
595 >>> @honk_elements(None)
596 ... class HonkNSElement(etree.ElementBase):
597 ... def honk(self):
598 ... return "HONK"
599
600 If the class has the same name as the tag, you can also leave out the call
601 and use the blank decorator instead:
602
603 .. sourcecode:: pycon
604
605 >>> @honk_elements
606 ... class honkel(HonkNSElement):
607 ... @property
608 ... def honking(self):
609 ... return self.get('honking') == 'true'
610
611 >>> xml = '<honkel xmlns="http://hui.de/honk" honking="true"><bla/><!--comment--></honkel>'
612 >>> honk_element = etree.fromstring(xml, parser)
613
614 >>> print(type(honk_element))
615 <class 'honkel'>
616 >>> print(type(honk_element[0]))
617 <class 'HonkNSElement'>