?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/4/26 12:49
# @Author : @linlianqin
# @Site :
# @File : test1.py
# @Software: PyCharm
# @description:
import xml.etree.ElementTree as ETdef xmli(xmlpath):xmlTree = ET.parse(xmlpath) # 解析xml文件root = xmlTree.getroot() # 獲得xml根節點size = root.find('size') # 查找size結點# 主要這里一定是findall,查找所有的object結點,也就是標注框的信息,否則用find返回的是Nonetypeobjects = root.findall('object') # 查找所有的object結點for obj in objects:bbox = obj.find('bndbox')# 修改相應結點的值bbox.find('ymin').text = str(222)bbox.find('ymax').text = str(222)return xmlTree # 返回更新后的xml文件句柄xmlTree = xmli(r'test.xml')
xmlTree.write('_flip_updown.xml') # 存儲新的xml文件
?
以下轉自:python VOC格式的xml文件解析
python解析XML常見的有三種方法:
??? xml.dom.*模塊,它是W3C DOM API的實現,若需要處理DOM API則該模塊很適合;
??? xml.sax.*模塊,它是SAX API的實現,這個模塊犧牲了便捷性來換取速度和內存占用,SAX是一個基于事件的API,這就意味著它可以“在空中”處理龐大數量的的文檔,不用完全加載進內存;
??? xml.etree.ElementTree模塊(簡稱 ET),它提供了輕量級的Python式的API,相對于DOM來說ET 快了很多,而且有很多令人愉悅的API可以使用,相對于SAX來說ET的ET.iterparse也提供了 “在空中” 的處理方式,沒有必要加載整個文檔到內存,ET的性能的平均值和SAX差不多,但是API的效率更高一點而且使用起來很方便。
?
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# get annotation object bndbox location
try:import xml.etree.cElementTree as ET #解析xml的c語言版的模塊
except ImportError:import xml.etree.ElementTree as ET##get object annotation bndbox loc start
def GetAnnotBoxLoc(AnotPath):#AnotPath VOC標注文件路徑tree = ET.ElementTree(file=AnotPath) #打開文件,解析成一棵樹型結構root = tree.getroot()#獲取樹型結構的根ObjectSet=root.findall('object')#找到文件中所有含有object關鍵字的地方,這些地方含有標注目標ObjBndBoxSet={} #以目標類別為關鍵字,目標框為值組成的字典結構for Object in ObjectSet:ObjName=Object.find('name').textBndBox=Object.find('bndbox')x1 = int(BndBox.find('xmin').text)#-1 #-1是因為程序是按0作為起始位置的y1 = int(BndBox.find('ymin').text)#-1x2 = int(BndBox.find('xmax').text)#-1y2 = int(BndBox.find('ymax').text)#-1BndBoxLoc=[x1,y1,x2,y2]if ObjBndBoxSet.__contains__(ObjName):ObjBndBoxSet[ObjName].append(BndBoxLoc)#如果字典結構中含有這個類別了,那么這個目標框要追加到其值的末尾else:ObjBndBoxSet[ObjName]=[BndBoxLoc]#如果字典結構中沒有這個類別,那么這個目標框就直接賦值給其值吧return ObjBndBoxSet
##get object annotation bndbox loc end
其他xml文件的操作——寫入、更新、讀取請參考:python解析xml文件(解析、更新、寫入)