文件1.xml如下:
<annotation>
<folder>fist</folder>
<filename>0.png</filename>
<path>E:/data/0.png</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>640</width>
<height>480</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>fist</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>65</xmin>
<ymin>198</ymin>
<xmax>308</xmax>
<ymax>480</ymax>
</bndbox>
</object>
</annotation>
使用ElementTree解析如下:
from xml.etree import ElementTree
class Example:
pass
example = Example()
root=ElementTree.parse("1.xml") #parse方法读取xml文件,得到元素树,root为根节点<annotation>
size = root.find('size') #size 为根节点下<size>节点
box = root.find('object').find('bndbox') #box 根节点下<object><bndbox>节点
example.path = root.find('path').text
example.width = size.find('width').text
example.height = size.find('height').text
example.depth = size.find('depth').text
example.xmin = box.find('xmin').text
example.xmax = box.find('xmax').text
example.ymin = box.find('ymin').text
example.ymax = box.find('ymax').text