Alex Rivera | Logout

Testing Equivalence of xml.etree.ElementTree

Asked 2011-10-26T15:57:07.307
36

I'm interested in equivalence of two xml elements; and I've found that testing the tostring of the elements works; however, that seems hacky.

Is there a better way to test equivalence of two etree Elements?

Comparing Elements directly:

import xml.etree.ElementTree as etree
h1 = etree.Element('hat',{'color':'red'})
h2 = etree.Element('hat',{'color':'red'})

h1 == h2  # False

Comparing Elements as strings:

etree.tostring(h1) == etree.tostring(h2)  # True
Edit
Report

2 Answers

3

Believe it or not that is actually the best way to handle comparing two nodes if you don't know how many children each may have and you want to include all children in the search.

Of course, if you simply have a childless node like the one you are demonstrating, you can simply compare the tag, attrib, and tail properties:

if h1.tag == h2.tag and h1.attrib == h2.attrib and h1.tail == h2.tail:
    print("h1 and h2 are the same")
else
    print("h1 and h2 are the different")

I don't see any major benefit of this over using tostring, however.

answered 2011-10-26T16:59:28.490
2

An usual way to compare complex structures is to dump them in a common unique textual representation and compare the resulting strings for equality.

To compare two received json strings, you would convert them to json objects, and then convert them back to strings (with the same convertor) and compare. I did it to check json feeds, it works well.

For XML, it is almost the same, but you may have to handle (strip? remove?) the ".text" parts (the text, blank or not, that may be found outside tags).

So in short, your solution is not a hack, as long as you make sure two equivalent XMLs (according to your context) will have the same string representation.

answered 2011-10-26T16:21:35.950

Your Answer