版权声明:@liaogaoyong https://blog.csdn.net/qq_42455710/article/details/88872577
话不多说直接上代码
from xml.etree import ElementTree as ET
#新文件路径与旧文件路径
NewFilePath = "D:\parseXml\\trans.xml"#新文件路径
OldFilePath = "D:\parsexml1\\trans.xml"#旧文件路径
# 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__()
oldattr.insert(0,OldRoot.attrib)
attr.clear()
# 调用递归函数生成新(新生成的测试)文件需要的xml标签与标签个数
newattr = newattrList(NewRoot)
newtags = tags.__len__()-oldtags
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))