Python 基于xml.etree.ElementTree实现XML对比示例详解
作者:授客 发布时间:2022-02-24 12:25:53
标签:Python,xml.etree.ElementTree,XML
测试环境
Python 3.6
Win10
代码实现
#!/usr/bin/env python 3.4.0
#-*- encoding:utf-8 -*-
__author__ = 'shouke'
import xml.etree.ElementTree as ET
def compare_xml_node_attributes(xml_node1, xml_node2):
result = []
node1_attributes_dict = xml_node1.attrib
node2_attributes_dict = xml_node2.attrib
for attrib1, value in node1_attributes_dict.items():
value2 = node2_attributes_dict.get(attrib1)
if value == value2:
node2_attributes_dict.pop(attrib1)
else:
if value2:
attrib2 = attrib1
node2_attributes_dict.pop(attrib2)
else:
attrib2 = '不存在'
result.append('结点1属性:{attrib1} 值:{value1},结点2属性:{attrib1} 值:{value2}'.format(attrib1=attrib1 or '不存在',
value1=value or '不存在',
attrib2=attrib2,
value2=value2 or '不存在'))
for attrib2, value2 in node2_attributes_dict.items():
result.append('结点1属性:{attrib1} 值:{value1},结点2属性:{attrib1} 值:{value2}'.format(attrib1='不存在',
value1='不存在',
attrib2=attrib2,
value2=value2))
return result
def compare_xml_node_children(xml_node1, xml_node2, node1_xpath, node2_xpath):
def get_node_children(xml_node, node_xpath):
result = {}
for child in list(xml_node):
if child.tag not in result:
result[child.tag] = [{'node':child, 'xpath': '%s/%s[%s]' % (node_xpath, child.tag, 1)}]
else:
result[child.tag].append({'node':child, 'xpath': '%s/%s[%s]' % (node_xpath, child.tag, len(result[child.tag])+1)})
return result
result = []
children_of_node1_dict = get_node_children(xml_node1, node1_xpath)
children_of_node2_dict = get_node_children(xml_node2, node2_xpath)
temp_list1 = []
temp_list2 = []
for child_tag, child_node_list in children_of_node1_dict.items():
second_child_node_list = children_of_node2_dict.get(child_tag, [])
if not second_child_node_list:
# 获取xml1中比xml2中多出的子结点
for i in range(0, len(child_node_list)):
temp_list1.append('%s/%s[%s]' % (node1_xpath, child_node_list[i]['node'].tag, i+1))
continue
for first_child, second_child in zip(child_node_list, second_child_node_list):
result.extend(compare_xml_nodes(first_child['node'], second_child['node'], first_child['xpath'], second_child['xpath']))
# 获取xml2中对应结点比xml1中对应结点多出的同名子结点
for i in range(len(child_node_list), len(second_child_node_list)):
temp_list2.append('%s/%s[%s]' % (node2_xpath, second_child_node_list[i]['node'].tag, i+1))
children_of_node2_dict.pop(child_tag)
if temp_list1:
result.append('子结点不一样:xml1结点(xpath:{xpath1})比xml2结点(xpath:{xpath2})多了以下子结点:\n{differences}'.format (xpath1=node1_xpath,
xpath2=node2_xpath,
differences='\n'.join(temp_list1)))
# 获取xml2比xml1中多出的子结点
for child_tag, child_node_list in children_of_node2_dict.items():
for i in range(0, len(child_node_list)):
temp_list2.append('%s/%s[%s]' % (node1_xpath, child_node_list[i]['node'].tag, i+1))
if temp_list2:
result.append('子结点不一样:xml1结点(xpath:{xpath1})比xml2结点(xpath:{xpath2})少了以下子结点:\n{differences}'.format (xpath1=node1_xpath,
xpath2=node2_xpath,
differences='\n'.join(temp_list2)))
return result
def compare_xml_nodes(xml_node1, xml_node2, node1_xpath='', node2_xpath=''):
result = []
# 比较标签
if xml_node1.tag != xml_node2.tag:
result.append('标签不一样:xml1结点(xpath:{xpath1}):{tag1},xml2结点(xpath:{xpath2}):{tag2}'.format (xpath1=node1_xpath,
tag1=xml_node1.tag,
xpath2=node2_xpath,
tag2=xml_node2.tag))
# 比较文本
if xml_node1.text != xml_node2.text:
result.append('文本不一样:xml1结点(xpath:{xpath1}):{text1},xml2结点(xpath:{xpath2}):{text2}'.format (xpath1=node1_xpath,
tag1=xml_node1.text or '',
xpath2=node2_xpath,
tag2=xml_node2.text or ''))
# 比较属性
res = compare_xml_node_attributes(xml_node1, xml_node2)
if res:
result.append('属性不一样:xml1结点(xpath:{xpath1}),xml2结点(xpath:{xpath2}):\n{differences}'.format (xpath1=node1_xpath,
xpath2=node2_xpath,
differences='\n'.join(res)))
# 比较子结点
res = compare_xml_node_children(xml_node1, xml_node2, node1_xpath, node2_xpath)
if res:
result.extend(res)
return result
def compare_xml_strs(xml1_str, xml2_str, mode=3):
'''
@param: mode 比较模式,预留,暂时没用。目前默认 xml 子元素如果为列表,则列表有序列表,按序比较
'''
root1 = ET.fromstring(xml1_str.strip())
root2 = ET.fromstring(xml2_str.strip())
return compare_xml_nodes(root1, root2, '/%s' % root1.tag, '/%s' % root2.tag)
测试运行
xml_str1 = '''
<?xml version = "1.0" encoding="utf-8" ?>
<data>
<country name="Liechtenstein">
<rangk>1</rangk>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" ></neighbor>
<neighbor name="Switzerland" direction="W" ></neighbor>
</country>
<country name="Singpore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" ></neighbor>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W" ></neighbor>
<neighbor name="Colombia" direction="W" ></neighbor>
</country>
</data>
'''
xml_str2 = '''
<?xml version = "1.0" encoding="utf-8" ?>
<data>
<country name="Liechtenstein">
<rangk>1</rangk>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E" ></neighbor>
<neighbor name="Switzerland" direction="W" ></neighbor>
</country>
<country name="Singpore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N" ></neighbor>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W" ></neighbor>
<neighbor name="Colombia" direction="W" ></neighbor>
</country>
</data>
'''
xml_str3 = '''
<?xml version = "1.0" encoding="utf-8" ?>
<data>
<class name="computer">
<rangk>1</rangk>
<year>unknow</year>
<addr>sz</addr>
<book name="java programming" price="10" ></book>
<book name="python programming" price="10" ></book>
</class>
<class name="philosophy">
<rangk>2</rangk>
<year>unknown</year>
<book name="A little history of philosophy" price="15" ></book>
<book name="contemporary introduction" price="15" ></book>
</class>
<class name="history">
<rangk>3</rangk>
<year>unknown</year>
<addr>other addr</addr>
<book name="The South China Sea" price="10" ></book>
<book name="Chinese Among Others" price="10" ></book>
</class>
</data>
'''
xml_str4 = '''
<?xml version = "1.0" encoding="utf-8" ?>
<data>
<class name="computer">
<year>unknow</year>
<addr>sz</addr>
<book name="java programming" price="10" ></book>
<book name="python programming" price="10" ></book>
</class>
<class name="philosophy">
<year>unknown</year>
<addr>other addr</addr>
<book name="A little history of philosophy" price="15" ></book>
<book name="contemporary introduction" price="16" ></book>
</class>
</data>
'''
if __name__ == '__main__':
res_list = compare_xml_strs(xml_str1, xml_str2)
if res_list:
print('xml1和xml2不一样:\n%s' % '\n'.join(res_list))
else:
print('xml1和xml2一样')
res_list = compare_xml_strs(xml_str3, xml_str4)
if res_list:
print('xml3和xml4不一样:\n%s' % '\n'.join(res_list))
else:
print('xml3和xml4一样')
运行结果
xml1和xml2一样 xml3和xml4不一样: 子结点不一样:xml1结点(xpath:/data/class[1])比xml2结点(xpath:/data/class[1])多了以下子结点: /data/class[1]/rangk[1] 属性不一样:xml1结点(xpath:/data/class[2]/book[2]),xml2结点(xpath:/data/class[2]/book[2]): 结点1属性:price 值:15,结点2属性:price 值:16 子结点不一样:xml1结点(xpath:/data/class[2])比xml2结点(xpath:/data/class[2])多了以下子结点: /data/class[2]/rangk[1] 子结点不一样:xml1结点(xpath:/data/class[2])比xml2结点(xpath:/data/class[2])少了以下子结点: /data/class[2]/addr[1]
来源:https://www.cnblogs.com/shouke/p/16975021.html


猜你喜欢
- 有时候我们会有这样的一个需求:我们定义了一个 Python 的方法,方法接收一些参数,但是调用的时候想将这些参数用命令行暴露出来。比如说这里
- 如果你的数据量有几十万条,用户又搜索一些很通俗的词,然后要依次读最后几页重温旧梦。mysql该很悲壮的不停操作硬盘。 所以,可以试着让mys
- 最近做的asp.netMVC项目中需要对数据列表进行分类,这个本来就是基于bootstrap开发的后台,因此也就想着bootstrap是否有
- 01、介绍在编程语言中,字符串是一种重要的数据结构。在 Golang 语言中,因为字符串只能被访问,不能被修改,所以,如果我们在 Golan
- 安装pyqt5wind@wind-ThinkPad-X250:~/Downloads/PyQt5_gpl-5.12.2$ python3 -
- 对于Python开发用户来讲,安装第三方库是家常便饭,下面提供两种安装方式pycharm软件安装1.打开file>setting2.点
- 图片太大了,上百张图用photoshop改太慢,就想到用python写个简单的批处理。功能简单就是把原图按比例缩小# -*- coding:
- 一、说明 关于matplotlib的scatter函数有许多活动参数,如果不专门注解,是
- 一、三种数据文件的读取二、csv、tsv、txt 文件读取1)CSV文件读取:语法格式:pandas.read_csv(文件路径)CSV文件
- Date 日期和时间对象1. 介绍Date对象,是操作日期和时间的对象。Date对象对日期和时间的操作只能通过方法。2. 构造函数2.1 n
- python中列表的常见操作列表元组的简单操作前面我们已经学过了关于len()函数、赋值运算符及身份运算符的使用,下面简单回顾一下这些在列表
- 作为临时测试用python命令来搭建web测试是最好不过的选择了;CD切换到当前目录只需要一句python命令就迅速搭建好了简单的web服务
- 直接使用word文档已经难不倒大家了,有没有想过用python构建一个word文档写点文章呢?当然这个文章的框架需要我们用代码一点点的建立,
- 楔子shutil 是一个 Python 内置模块,该模块对文件的复制、删除和压缩等操作都提供了非常方便的支持。下面来详细介绍一下该模块的用法
- IN主要用于传入参数,可以是变量,常量,表达式,在子程序内部不能改变其值. 代码如下:DECLARE n NUMBER := 10; PRO
- 前言文章包括下几点:考点--操作SQLite数据库:创建SQLite数据库;向表中插入记录;其他数据库操作。面试题:1.面试题一:如何创建S
- 排序,是许多编程语言中经常出现的问题。同样的,在Python中,如何是实现排序呢?(以下排序都是基于列表来实现)一、使用Python内置函数
- 今天打算通过绘制正弦和余弦函数,从默认的设置开始,一步一步地调整改进,让它变得好看,变成我们初高中学习过的图象那样。通过这个过程来学习如何进
- 1. 数据抽取的概念2. 数据的分类3. JSON数据概述及解析3.1 JSON数据格式3.2 解析库jsonjson模块是Python内置
- 问题:python2.7 查询或者插入中文数据在mysql中的时候出现中文乱码---可能情况:1.mysql数据库各项没有设置编码,默认为&