lxml, comparing nodes

Fredrik Lundh fredrik at pythonware.com
Wed Jul 23 16:04:24 EDT 2008


code_berzerker wrote:

>> Your requirements for a single Element are simple enough to write it in three
>> to five lines of Python code (depending on your definition of equality).
>> Checking this equality recursively is another two to three lines. Not complex
>> enough to be considered a wheel in the first place.
> 
> Forgive my ignorance as I am new to both Python and lxml ;)

off the top of my head (untested):

 >>> def equal(a, b):
...     if a.tag != b.tag or a.attrib != b.attrib:
...         return False
...     if a.text != b.text or a.tail != b.tail:
...         return False
...     if len(a) != len(b):
...         return False
...     if any(not equal(a, b) for a, b in zip(a, b)):
...         return False
...     return True

this should work for arbitrary ET implementations (lxmk, xml.etree, ET, 
etc).  tweak as necessary.

</F>




More information about the Python-list mailing list