Python - xml模块

xml模块

处理文档:
Python - xml模块

import xml.etree.ElementTree as ET

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

Python - xml模块

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

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

Python - xml模块

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

Python - xml模块

也可以用for循环取数据:

Python - xml模块

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

Python - xml模块

k.text

Python - xml模块

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

Python - xml模块

修改year节点的属性和值:

Python - xml模块
Python - xml模块

删除:

Python - xml模块

运行后显示:

Python - xml模块

新建一个xml文档

Python - xml模块

代码运行后:

Python - xml模块

猜你喜欢

转载自blog.51cto.com/11533525/2402122