背景:给定两个 xml 字符串,然后比较两个 xml 相同层级、相同名字(在 ElementTree 组建里叫 tag)的节点的值是否一致,相同层级不能含有多个名字相同的子节点(即 tag 不能重复),如果发现有值不一致的,返回 True
def compare_xml(left_nodes, right_nodes, key_info='.'): | |
left_len, right_len = len(left_nodes), len(right_nodes) | |
for i in range(left_len): | |
left_node_tag, left_node_text = left_nodes[i].tag, left_nodes[i].text | |
for j in range(right_len): | |
right_node_tag, right_node_text = right_nodes[j].tag, right_nodes[j].text | |
if right_node_tag == left_node_tag: | |
if right_node_text == left_node_text: | |
s = '%s/%s' % (key_info, left_node_tag) | |
if len(left_nodes[i].getchildren()) > 0: | |
return compare_xml(left_nodes[i], right_nodes[j], s) | |
else: | |
s = '%s/%s' % (key_info, left_node_tag) | |
print(s) | |
return True | |
if __name__ == '__main__': | |
xml_str1 = "<site>" \ | |
" <tools>" \ | |
" <name>jalen.site</name>" \ | |
" </tools>" \ | |
" <metaData>" \ | |
" <server>aliyun</server>" \ | |
" </metaData>" \ | |
"</site>" | |
xml_str2 = "<site>" \ | |
" <metaData>" \ | |
" <server><name>jalen.site11</name></server>" \ | |
" </metaData>" \ | |
" <tools>" \ | |
" <name>jalen.site</name>" \ | |
" </tools>" \ | |
"</site>" | |
left_root = ElementTree.fromstring(xml_str1) | |
right_root = ElementTree.fromstring(xml_str2) | |
left_nodes = left_root.getchildren() | |
right_nodes = right_root.getchildren() | |
res = compare_xml(left_nodes, right_nodes) | |
if res: | |
print('difference.') | |
else: | |
print('same.') |