测试xml.etree.ElementTree的等效项 [英] Testing Equivalence of xml.etree.ElementTree

查看:60
本文介绍了测试xml.etree.ElementTree的等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对两个xml元素的等效性感兴趣;而且我发现测试元素的字符串是可行的;

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.

有没有更好的方法来测试两个etree元素的等效性?

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

直接比较元素:

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))

这篇关于测试xml.etree.ElementTree的等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆