使用python对xml文件属性的修改
import xml.dom.minidom
import os
path='/workspace/head_detect/LFD-A-Light-and-Fast-Detector/Head_train/data/SCUT_HEAD_Part_B/Annotations1' # 原来xml文件存放的路径
sv_path='/workspace/head_detect/LFD-A-Light-and-Fast-Detector/Head_train/data/SCUT_HEAD_Part_B/Annotations' # 修改后的xml文件存放路径
files=os.listdir(path)
# print("files:",files) # xml文件名列表
print("start write xml")
for xmlFile in files:
dom=xml.dom.minidom.parse(os.path.join(path,xmlFile)) #打开xml文件,送到dom解析
root=dom.documentElement #得到文档元素对象
a,b = os.path.splitext(xmlFile)
item1=root.getElementsByTagName('path') # 获取path这一node名字及相关属性值
# a,b = os.path.splitext(xmlFile)
# for j in item:
# i.firstChild.data += (a + '.jpg')
# item=root.getElementsByTagName('path')
# a,b = os.path.splitext(xmlFile) # 并没有取filename标签名,而直接用的文件名,保险期间还是用filename
for i in item1:
i.firstChild.data='/workspace/head_detect/LFD-A-Light-and-Fast-Detector/Head_train/data/SCUT_HEAD_Part_B/JPEGImages/' # xml文件对应的图片路径
for j in item1:
i.firstChild.data += (a + '.jpg')
item2=root.getElementsByTagName('filename')
for i in item2:
i.firstChild.data = (a + '.jpg')
with open(os.path.join(sv_path,xmlFile),'w') as fh:
dom.writexml(fh)
item3=root.getElementsByTagName('folder')
for i in item3:
i.firstChild.data = "JPEGImages"
with open(os.path.join(sv_path,xmlFile),'w') as fh:
dom.writexml(fh)
print("end write xml")
|