Python读取xml文件(xml.etree.ElementTree)

# code reading xml file
import xml.etree.ElementTree as ET

tree = ET.parse('./test.xml')
root = tree.getroot()
for ob in root.iter('object'):
    for name in ob.iter('name'):
        print('name ',name.text)
    for pose in ob.iter('pose'):
        print('pose ',pose.text)
    for trun in ob.iter('truncated'):
        print('trun ', trun.text)
    for diff in ob.iter('difficult'):
        print('diff ', diff.text)
    for bndbox in ob.iter('bndbox'):
        for l in bndbox:
            print(l.text)
# result:
name  bottle
pose  Unspecified
trun  0
diff  0
288
224
330
328
# XML file for test
<annotation>
    <folder>VOC2007folder>
    <filename>006500.jpgfilename>
    <source>
        <database>The VOC2007 Databasedatabase>
        <annotation>PASCAL VOC2007annotation>
        <image>flickrimage>
        <flickrid>319318625flickrid>
    source>
    <owner>
        <flickrid>El Mitchflickrid>
        <name>?name>
    owner>
    <size>
        <width>500width>
        <height>333height>
        <depth>3depth>
    size>
    <segmented>0segmented>
    <object>
        <name>bottlename>
        <pose>Unspecifiedpose>
        <truncated>0truncated>
        <difficult>0difficult>
        <bndbox>
            <xmin>288xmin>
            <ymin>224ymin>
            <xmax>330xmax>
            <ymax>328ymax>
        bndbox>
    object>
annotation>

你可能感兴趣的:(python)