xml文件读取

xml文件如下:

<annotation>
    <folder>bnrc</folder>
    <filename>jena_000000_000019_leftImg8bit.png</filename>
    <path>/home/bnrc/jena_000000_000019_leftImg8bit.png</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>2048</width>
        <height>1024</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>car</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>646</xmin>
            <ymin>415</ymin>
            <xmax>844</xmax>
            <ymax>559</ymax>
        </bndbox>
    </object>
    <object>
        <name>car</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>978</xmin>
            <ymin>404</ymin>
            <xmax>1096</xmax>
            <ymax>503</ymax>
        </bndbox>
    </object>
    <object>
        <name>car</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>864</xmin>
            <ymin>404</ymin>
            <xmax>940</xmax>
            <ymax>463</ymax>
        </bndbox>
    </object>
    <object>
        <name>car</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>924</xmin>
            <ymin>396</ymin>
            <xmax>968</xmax>
            <ymax>435</ymax>
        </bndbox>
    </object>
</annotation>

代码如下:

import xml.etree.ElementTree as ET
import os
import sys



xmlFilePath = os.path.abspath("jena_000000_000019_leftImg8bit.xml.xml")
print(xmlFilePath)
tree = ET.parse(xmlFilePath)


root = tree.getroot()
root_child_length = len(root.getchildren()) 
child = root.getchildren()
for i in range(6,root_child_length):
    child_box = child[i].getchildren()[4]
    x_min = child_box.getchildren()[0].text
    y_min = child_box.getchildren()[1].text
    x_max = child_box.getchildren()[2].text
    y_max = child_box.getchildren()[3].text
    print x_min,y_min,x_max,y_max

Element对象有标签、属性和值,访问分别是:

tag = element.tag
attrib = element.attrib
value = element.text

 

posted @ 2018-04-12 11:15  有梦就要去实现他  阅读(239)  评论(0编辑  收藏  举报