xml模块

处理文档:
Python - xml模块_第1张图片

import xml.etree.ElementTree as ET

tree = ET.parse('xmlfile')    # ET.parse() 解析xml文档
root = tree.getroot()        # 获取根节点
print(root.tag)          # root.tag 获取根节点标签   这里是data

Python - xml模块_第2张图片

for i in root:
    print(i.tag)        # 获取根节点下的标签
    print(i.attrib)     # 获取根节点下的标签属性

标签>>: country 、标签属性>>: {'name': 'Panama'}

Python - xml模块_第3张图片

同样的 country 下也有标签、属性等:

Python - xml模块_第4张图片

也可以用for循环取数据:

Python - xml模块_第5张图片

被标签包围的数据取出来:

Python - xml模块_第6张图片

k.text

Python - xml模块_第7张图片

root.iter('year') 遍历year节点:

Python - xml模块_第8张图片

修改year节点的属性和值:

Python - xml模块_第9张图片
Python - xml模块_第10张图片

删除:

Python - xml模块_第11张图片

运行后显示:

Python - xml模块_第12张图片

新建一个xml文档

Python - xml模块_第13张图片

代码运行后:

Python - xml模块_第14张图片