python - 测试 xml.etree.ElementTree 的等价性

标签 python python-3.x elementtree

我对两个 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/

相关文章:

python - 在 python 进程之间传递二进制数据

python - 我如何在 python 中拆分列表

attributes - 如何更改 ElementTree 属性键?

python - 如何在 python 中使用 ElementTree 访问包含命名空间的 xml 中的属性值

python - Seaborn 在同一个散点图上绘制两个数据集

Python ElementTree 从根目录中删除元素时出错

python - 根据从另一个 DataFrame 构建的条件列表选择 Pandas DataFrame 的子集

python - Pandas 将带有 unix 时间戳(以毫秒为单位)的行转换为日期时间

python - read() 在 NUL 字符后停止

python - 在 Python 2.7 中使用带有 mysql.connector 的参数化查询