导包
from xml.etree.ElementTree import parse, Element
import os
新增单个类别的单条记录
save_Xml_Path = r'C:\Users\YYQ\Desktop\3'
tmp_1 = {
'name': 'broom_dustpan',
'pose': 'Unspecified',
'truncated': '0',
'difficult': '0',
'bndbox': {
'xmin': '1007',
'ymin': '299',
'xmax': '1100',
'ymax': '488',
}
}
解析xml
def parse_xml(fileName,dic):
doc = parse(fileName)
root = doc.getroot()
element = Element('object')
for i,v in dic.items():
e = Element(i)
if isinstance(v, str):
e.text = v
if isinstance(v, dict):
for i1, v1 in v.items():
e2 = Element(i1)
e2.text = v1
e.append(e2)
element.append(e)
root.append(element)
name = fileName.split('\\')[-1]
xml_name = save_Xml_Path + '/' + name
# print(xml_name)
doc.write(xml_name, xml_declaration=True)
主程序调用
filePath = r'C:\Users\YYQ\Desktop\2'
for i in os.listdir(filePath):
fileName = os.path.join(filePath, i)
print(fileName)
parse_xml(fileName, tmp_1)