代码:读取xml文件.py
# xml文件内容如下:
"""
<annotation>
<folder>VOC2007</folder>
<filename>000005.jpg</filename>
<source>
<database>The VOC2007 Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>325991873</flickrid>
</source>
<owner>
<flickrid>archintent louisville</flickrid>
<name>?</name>
</owner>
<size>
<width>500</width>
<height>375</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>chair</name>
<pose>Rear</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>263</xmin>
<ymin>211</ymin>
<xmax>324</xmax>
<ymax>339</ymax>
</bndbox>
</object>
<object>
<name>chair</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>165</xmin>
<ymin>264</ymin>
<xmax>253</xmax>
<ymax>372</ymax>
</bndbox>
</object>
<object>
<name>chair</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>1</difficult>
<bndbox>
<xmin>5</xmin>
<ymin>244</ymin>
<xmax>67</xmax>
<ymax>374</ymax>
</bndbox>
</object>
<object>
<name>chair</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>241</xmin>
<ymin>194</ymin>
<xmax>295</xmax>
<ymax>299</ymax>
</bndbox>
</object>
<object>
<name>chair</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>1</difficult>
<bndbox>
<xmin>277</xmin>
<ymin>186</ymin>
<xmax>312</xmax>
<ymax>220</ymax>
</bndbox>
</object>
</annotation>
"""
import xml.etree.ElementTree as ET
# xmlPath = r'000020.xml'
xmlPath = r'000005.xml'
xmlFile = open(xmlPath)
tree = ET.parse(xmlFile)
# tree = ET.parse(xmlPath) # 以上两种参数均可,可以是文件的路径或者文件对象
root = tree.getroot()
for obj in root.iter('object'):
difficult = obj.find('difficult').text
classType = obj.find('name').text
bndbox = obj.find('bndbox')
xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text)
info = \
"difficult:{0:^4}classType:{1:^10}xmin:{2:^6}ymin:{3:^6}xmax:{4:^6}ymax:{5:^6}".format(
difficult,classType,xmin,ymin,xmax,ymax)
print(info)
xmlFile.close()
控制台输出结果展示:
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\chenxuqi\Desktop\新建文件夹\test> & 'D:\Python\Python37\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.11.358366026\pythonFiles\lib\python\debugpy\launcher' '52254' '--' 'c:\Users\chenxuqi\Desktop\新建文件夹\test\读取xml文件.py'
difficult: 0 classType: chair xmin: 263 ymin: 211 xmax: 324 ymax: 339
difficult: 0 classType: chair xmin: 165 ymin: 264 xmax: 253 ymax: 372
difficult: 1 classType: chair xmin: 5 ymin: 244 xmax: 67 ymax: 374
difficult: 0 classType: chair xmin: 241 ymin: 194 xmax: 295 ymax: 299
difficult: 1 classType: chair xmin: 277 ymin: 186 xmax: 312 ymax: 220
PS C:\Users\chenxuqi\Desktop\新建文件夹\test>
源代码参考链接: bubbliiiing/ssd-pytorch