遇到问题xml文件读写,没有子节点需要新建ChildNode。

 # -*- coding: utf-8 -*-
import os
import shutil
import xml.dom.minidom def correctxml(srcdir,finddir):
num = 0
list = os.listdir(srcdir)
for i in range(0,len(list)):
if list[i][-3:] == 'xml':
#print(list[i]) # 0863091.res
resdir = os.path.join(srcdir,list[i])
# C:\\Users\\Administrator\\Desktop\\两类错误图像\\有效期限\\答案错误\\0863091.res
restree = xml.dom.minidom.parse(resdir)
res = restree.documentElement
#value1 签发机构
#resvalue1 = res.getElementsByTagName('field')[1].getAttribute('value') resvalue1 = res.getElementsByTagName('Field')[6].childNodes[0].nodeValue
#value2 有效期限 .childNodes[0]
#resvalue2 = res.getElementsByTagName('field')[2].getAttribute('value')
#value3 签发日期
#resvalue3 = res.getElementsByTagName('field')[3].getAttribute('value')
#value4 有效期至
#resvalue4 = res.getElementsByTagName('field')[4].getAttribute('value')
if len(list[i]) == 11:
findpath = finddir + '\\' + list[i][:-7]
else:
findpath = finddir + '\\0' + list[i][:-7]
#findpath = finddir + '\\0' + list[i][:-7]
findlist = os.listdir(findpath) for j in range(0,len(findlist)):
if list[i][:-4] == findlist[j][:-4]:
xmldir = os.path.join(findpath,findlist[j])
#print(xmldir)
xmltree = xml.dom.minidom.parse(xmldir)
solutionxml = xmltree.documentElement
if solutionxml.getElementsByTagName('Field')[6].hasChildNodes():
solutionxml.getElementsByTagName('Field')[6].childNodes[0].nodeValue = resvalue1 # 存在节点直接赋值
else:
solutionxml.getElementsByTagName('Field')[6].appendChild(xmltree.createTextNode(resvalue1)) # 不存在节点新建节点
element = solutionxml.getElementsByTagName('Field')
print(element)
#solutionxml.getElementsByTagName('Field')[2].childNodes[0].nodeValue = resvalue2
#solutionxml.getElementsByTagName('Field')[3].childNodes[0].nodeValue = resvalue3
#solutionxml.getElementsByTagName('Field')[4].childNodes[0].nodeValue = resvalue4 with open(xmldir,'w', encoding='UTF-8') as fh:
xmltree.writexml(fh,newl='\n',encoding='UTF-8')
num = num + 1 # 计数
file1 = open(xmldir, 'r', encoding='utf-8') # 要去掉空行的文件
file2 = open('C:\\Users\\WT\\Desktop\\1.xml', 'w', encoding='utf-8') # 生成没有空行的文件
for line in file1.readlines():
line = line.lstrip("\n")
file2.write(line)
file1 = open(xmldir, 'w', encoding='utf-8')
file2 = open('C:\\Users\\WT\\Desktop\\1.xml', 'r', encoding='utf-8')
for line in file2.readlines():
file1.write(line)
print('修改了'+ xmldir) print(num) correctxml('C:\\Users\\WT\\Desktop\\tmp',
'D:\\标准样本库v2\\02 样本库\\02 标准答案\\06 机动车行驶证\\03 手机拍照\\01 自由拍照')

参考博客:https://blog.csdn.net/kongsuhongbaby/article/details/84869838

05-14 17:09