[lxml-dev] Custom Elements

Stefan Behnel stefan_ml at behnel.de
Wed Mar 21 20:22:24 CET 2007


Hi again,

Stefan Behnel wrote:
> Stephan Richter wrote:
>> class DirectiveLookup(etree.CustomElementClassLookup):
>>
>>     def lookup(self, type, doc, namespace, name):
>>         import pdb; pdb.set_trace()
>>         if name == 'foo1':
>>             return Directive1
>>         elif name == 'foo2':
>>             return Directive2
>>         return None
>>
>> However, in my case, the lookup also depends on the parent element in my case, 
>> because a tag with the same name can have different meanings in different 
>> contexts. (Don't ask, this is a specification requirement of RML. ;-)
>>
>> So here my question: How do I access the parent element?
> 
> That's a tricky one.

Correcting myself: wasn't that tricky after all. The trunk now has a new
module called "lxml.pyclasslookup" that provides a new lookup mechanism:

PythonElementClassLookup

You can subclass it and implement the method "lookup(self, doc, element)" to
find a suitable element class for "element". This last argument is an instance
of a lightweight Element proxy that implements most of the API of the standard
Element class of lxml.etree. The main differences are the lack of iteration
support and the bigger things like XPath etc. Just take that object, traverse
and analyse the tree as you see fit and return the element class that suits
your needs.

Have fun,
Stefan



More information about the lxml-dev mailing list