xml格式比较广泛,比如使用xml记录机器学习中的标签,本文主要介绍如何对xml文件进行增删改查操作
参考翻译自python官方网站xml使用说明
xml文件格式介绍
xml使用树形结构展示了一种比较自然的而又有层次感的数据格式文件,xml文件一般在机器学习标签格式存储比较常用。
下面通过例子进行介绍python如何增删改查xml文件
xml文件查找操作
需要操作的xml文件内容:
<annotation>
<folder>CP</folder>
<filename>IMG_3314.JPG</filename>
<path>D:\CP\IMG_3314.JPG</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>3024</width>
<height>4032</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>plate</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1307</xmin>
<ymin>1857</ymin>
<xmax>1791</xmax>
<ymax>2224</ymax>
</bndbox>
</object>
</annotation>
首先需要读取xml文件,然后获得树的根
import xml.etree.ElementTree as ET
tree = ET.parse('plate.xml') # 从文件中读取
root = tree.getroot() # 获取xml文件树的根
或者从字符串中读取xml文件:
root = ET.fromstring(plate_data_as_string)
假如需要获得根的标签,使用root.tag,或者通过root.attrib获取节点的属性,以及root.text获得节点的文本,假如node为: <tag=“attrib”>text</tag>
>>> node.tag # 节点的标签名
'tag'
>>> node.attrib # 标签名的属性值
'attrib'
>>> node.text # 获取节点的文本
'text'
- 获取根节点下的tag为’object’的节点,并找到object节点下的name,并打印text属性。
>>> for object in root.findall('object'):
... name = object.find('name')
... print name.text
'plate'
修改xml文件
ElementTree 提供了一个简单的方法去构建与写入xml文档,它write()方法提供了这样的意图。
一旦创建,一个Element 对象就能够直接被修改,其中text属性可以直接通过给 Element.text 赋值实现,而修改attributes属性则需要通过Element.set()方法,添加新的子类则需要 Element.append() 方法
>>> for object in root.iter('object'):
... new_object = int(object.text) + 1
... object.text = str(new_object)
... object.set('updated', 'yes')
>>> tree.write('output.xml')
- 也可以通过Element.remove()方法来删除节点
>>> for object in root.findall('object'):
... ob = object.find('name').text
... if ob != 'plate'
... root.remove(object)
>>> tree.write('output.xml')
知道这些常用的操作就可以灵活的使用xml文件了.