Python读xml文件

常用的标注文件除了采用json格式外,还有xml格式。最近有需要在Python中读xml文件,记录下来以备后用。

标注文件内容示例如下:

<?xml version="1.0" encoding="utf-8"?>
<annotations>
  <version>1.1</version>
  <image id="1" name="0001.jpg" width="1920" height="1080">
    <box label="person" occluded="0" xtl="1300.80" ytl="69.89" xbr="1344.74" ybr="213.33">
      <attribute name="state">man</attribute>
    </box>
    <box label="person" occluded="0" xtl="1164.29" ytl="96.66" xbr="1224.44" ybr="253.65">
      <attribute name="state">women</attribute>
    </box>
  </image>
</annotations>

读xml文件代码如下:

from xml.dom.minidom import parse

# parse the xml file
xml_data = parse('test.xml')
rootNode = xml_data.documentElement

nodes = rootNode.getElementsByTagName('image')
for node in nodes:
    boxes = node.getElementsByTagName('box')
    for box in boxes:
        xytb = [float(box.getAttribute('xtl')), float(box.getAttribute('ytl')),
                float(box.getAttribute('xbr')), float(box.getAttribute('ybr'))]
        attribute = str(box.getElementsByTagName('attribute')[0].childNodes[0].data)

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值