使用的XML文件如下:file.xml
<?xml version="1.0"?> <data name="ming"> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
导入模块
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/30 0030 18:18 # @Author : ming import xml.etree.ElementTree as ET
读取文件
result = ET.parse("file.xml") # 打开文件 root = result.getroot() # 获取根节点
打印一下根节点信息
print(root.tag, root.attrib) # 根节点标签和属性值 #运行结果:data {'name': 'ming'}
打印一下根节点的孩子节点
for i in root: # 循环根节点的孩子节点 print(i.tag, i.attrib) # 打印孩子节点的标签和属性值 print(i[0].tag, i[0].text) # 打印孙子节点中第一个节点的标签和属性值。多层节点都可以通过下标访问 # 运行结果: # country {'name': 'Singapore'} # rank 4 # country {'name': 'Panama'} # rank 68
findall 直接定位节点
for k in root.findall('country'): # 直接定位该节点 print(k.tag, k.attrib) # 打印孩子节点的标签和属性值 print(k[1].tag, k[1].text) # 打印孙子节点中第一个节点的标签和属性值。多层节点都可以通过下标访问 #运行结果 # country {'name': 'Singapore'} # year 2011 # country {'name': 'Panama'} # year 2011
iter 遍历所有节点
for m in root.iter(): # 遍历所有节点 print(m.tag, m.attrib, m.text) # 打印所有节点的标签、属性、值
data {'name': 'ming'}
country {'name': 'Singapore'}
rank {} 4
year {} 2011
gdppc {} 59900
neighbor {'name': 'Malaysia', 'direction': 'N'} None
country {'name': 'Panama'}
rank {} 68
year {} 2011
gdppc {} 13600
neighbor {'name': 'Costa Rica', 'direction': 'W'} None
neighbor {'name': 'Colombia', 'direction': 'E'} None