版权声明:@liaogaoyong https://blog.csdn.net/qq_42455710/article/details/88978430
from xml.etree import ElementTree as ET
import os
#新文件路径与旧文件路径
NewFilePath = "D:\parseXml\\00001_00003_00000.xml"#新文件路径
OldFilePath = "D:\parsexml1\\00001_00001_00000.xml"#旧文件路径
#获取指定磁盘下的xml文件列表#1
def getXmlFiledir(FindPath):
suffix='.xml'#文件后缀
FileList = []
FileNames = os.listdir(FindPath)
for filename in FileNames:
name, suf = os.path.splitext(filename) # =>文件名,文件后缀
if suf == suffix:
FileList.append(os.path.join(FindPath, filename)) # =>吧一串字符串组合成路径
return FileList
# xml文件中的标签列表
tags = []
attr = []
# 调用递归函数生成需要的xml标签与属性值
def root(childs):
for child in childs:
if (child.getchildren() is None):
break
else:
attr.append(child.attrib)
tags.append(child.tag)
root(child)
#调用递归函数获取新文件的属性值列表
def newattrList(NewRoot):
root(NewRoot)
newattr=attr.copy()
attr.clear()
return newattr
#调用递归函数获取旧文件的属性值列表
def oldattrList(OldRoot):
root(OldRoot)
oldattr=attr.copy()
return oldattr
#比对两个xml文件内容(属性值是否相同),标签数量是否相同(多少)
def compareToxml(NewFilePath,OldFilePath):
tag ={ 1 : "新的标签数量多" , 2 : "新的标签数量少", 3 : "属性值相同" , 4 : "属性值不相同" }
# 直接解析xml文件
NewTree = ET.parse(NewFilePath)
Oldtree = ET.parse(OldFilePath)
# 获取xml文件的根节点
NewRoot = NewTree.getroot()
OldRoot = Oldtree.getroot()
#调用递归函数生成旧(原)文件需要的xml标签与标签个数
oldattr =oldattrList(OldRoot)
oldtags = tags.__len__()
tags.clear()
oldattr.insert(0,OldRoot.attrib)
attr.clear()
# 调用递归函数生成新(新生成的测试)文件需要的xml标签与标签个数
newattr = newattrList(NewRoot)
newtags = tags.__len__()
tags.clear()
newattr.insert(0,NewRoot.attrib)
#返回标签数量多少
if (oldtags < newtags):
# 返回值为新的数量多
return tag.get(1)
elif (oldtags > newtags):
# 返回值为新的数量少
return tag.get(2)
#返回属性值是否相同
if(oldattr == newattr):
return tag.get(3)
return tag.get(4)
if __name__ == "__main__":
print(compareToxml(NewFilePath,OldFilePath))