[python 解析xml xml.etree.ElementTree]使用xml.etree.ElementTree解析xml文件

可以参考官网教程,详细的很!

实例 test.xml

<?xml version="1.0" encoding="utf-8"?>
<tagset name='123' label='hh>
   <image>
      <imageName>img/14_03.jpg</imageName>
      <address>341 Southwest 10th Avenue Portland OR</address>
      <Resolution x="1280" y="880"/>
      <taggedRectangles>
         <taggedRectangle height="75" width="236" x="375" y="253">
            <tag>LIVING</tag>
         </taggedRectangle>
         <taggedRectangle height="76" width="175" x="639" y="272">
            <tag>ROOM</tag>
         </taggedRectangle>
         <taggedRectangle height="87" width="281" x="839" y="283">
            <tag>THEATERS</tag>
         </taggedRectangle>
      </taggedRectangles>
   </image>
</tagset>

学会几个就行了

读取xml代码 1

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

读取xml代码 2

# with open('test.xml') as f:
#     country_data_as_string = f.read()

root = ET.fromstring(country_data_as_string)

.tag  读取标签名字

root.tag  # tagset

 .attrib 读取属性

root.attrib  # {'name':'123','label':'hhh'}

.get('xx') 获取指定的属性值

root.get('name')  # '123'

.text 标签中的读取文本

.find() 包含的标签

.findall() 全部的什么标签  'taggedRectangles/taggedRectangle' 可以递进

具体的使用方式

tree = ET.parse('test.xml')
root = tree.getroot()

data = {}
for child in tqdm(root.findall('image')):
    print(child.find('imageName').text)
    imageName = child.find('imageName').text
    data[imageName] = []
    for t in child.findall('taggedRectangles/taggedRectangle'):
        data[imageName].append({
            'x': int(t.get('x')),
            'y': int(t.get('y')),
            'w': int(t.get('width')),
            'h': int(t.get('height')),
            'label': t.find('tag').text
        })

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放飞自我的Coder

你的鼓励很棒棒哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值