Adam Endicott Adam Endicott - 12 days ago 8
Python Question

Comparing XML in a unit test in Python

I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).

Answer

First normalize 2 XML, then you can compare them. I've used the following using lxml

    obj1 = objectify.fromstring(expect)
    expect = etree.tostring(obj1)        
    obj2 = objectify.fromstring(xml)
    result = etree.tostring(obj2)        
    self.assertEquals(expect, result)
Comments