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

  • Post author:
  • Post category:python


可以参考

官网教程

,详细的很!

实例 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
        })



版权声明:本文为qq_39749966原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。