Pyhon如何读取xml文件

1、XML编辑器

XmlNoepad下载地址:https://microsoft.github.io/XmlNotepad/#install/

2、两种读取方法

2007_000032.xml文件:

<annotation>
 <folder>VOC2012</folder>
 <filename>2007_000032.jpg</filename>
<source>
 <database>The VOC2007 Database</database>
 <annotation>PASCAL VOC2007</annotation>
 <image>flickr</image>
 </source>
<size>
 <width>500</width>
 <height>281</height>
 <depth>3</depth>
 </size>
 <segmented>1</segmented>
<object>
 <name>aeroplane</name>
 <pose>Frontal</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
<bndbox>
 <xmin>104</xmin>
 <ymin>78</ymin>
 <xmax>375</xmax>
 <ymax>183</ymax>
 </bndbox>
 </object>
<object>
 <name>aeroplane</name>
 <pose>Left</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
<bndbox>
 <xmin>133</xmin>
 <ymin>88</ymin>
 <xmax>197</xmax>
 <ymax>123</ymax>
 </bndbox>
 </object>
<object>
 <name>person</name>
 <pose>Rear</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
<bndbox>
 <xmin>195</xmin>
 <ymin>180</ymin>
 <xmax>213</xmax>
 <ymax>229</ymax>
 </bndbox>
 </object>
<object>
 <name>person</name>
 <pose>Rear</pose>
 <truncated>0</truncated>
 <difficult>0</difficult>
<bndbox>
 <xmin>26</xmin>
 <ymin>189</ymin>
 <xmax>44</xmax>
 <ymax>238</ymax>
 </bndbox>
 </object>
 </annotation>
2.1 读取某个节点的值

读取节点size下的width和height
读取脚本:

import xml.etree.ElementTree as ET

tree = ET.parse('2007_000032.xml')

w = tree.find('size').find('width').text
h = tree.find('size').find('height').text

print(w)
print(h)

读取效果:
在这里插入图片描述

2.2 遍历读取某种节点的值

遍历读取节点object下的name和pose
读取脚本:

import xml.etree.ElementTree as ET

tree = ET.parse('2007_000032.xml')
objects = []
for obj in tree.findall('object'):
    obj_dict = dict()
    obj_dict['name'] = obj.find('name').text
    obj_dict['pose'] = obj.find('pose').text
    objects.append(obj_dict)
print(len(objects),objects)
print(objects[3]['name'])

读取效果:
在这里插入图片描述

参考:

https://blog.csdn.net/weixin_41896770/article/details/128426869

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值