我对两个 xml 元素的等价性感兴趣;我发现测试元素的 tostring 是有效的;但是,这似乎很老套。
有没有更好的方法来测试两个 etree 元素的等价性?
直接比较元素:
import xml.etree.ElementTree as etree
h1 = etree.Element('hat',{'color':'red'})
h2 = etree.Element('hat',{'color':'red'})
h1 == h2 # False
将元素作为字符串进行比较:
etree.tostring(h1) == etree.tostring(h2) # True
最佳答案
这个比较功能对我有用:
def elements_equal(e1, e2):
if e1.tag != e2.tag: return False
if e1.text != e2.text: return False
if e1.tail != e2.tail: return False
if e1.attrib != e2.attrib: return False
if len(e1) != len(e2): return False
return all(elements_equal(c1, c2) for c1, c2 in zip(e1, e2))
关于python - 测试 xml.etree.ElementTree 的等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7905380/