下面使用xml.etree.ElementTree来解析xml
step1:首先定义xml文件test.xml,格式和内容如下:
<?xml version="1.0" encoding="ISO-8859-1"?> <data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <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>
step2:导入xml库
import xml.etree.ElementTree as ET
step3:实例化Element对象
tree = ET.ElementTree()
step4:载入XML文件
tree.parse("test.xml")
此时已经完成xml的加载,接下来就可以操作tree了
step5:现在开始操作xml树(操作xml文件的内容)
1)输出xml文件的树的根节点
print(tree.tag) # 但是此时会报错,AttributeError: 'ElementTree' object has no attribute 'tag'
解决方案如下:
tree = tree.getroot() t = ET.tostring(tree) t = t.lower() tree = ET.fromstring(t) print(tree) # 此时输出根节点的tag
2)可以遍历子节点
childtag = tree[0].tag # 根目录的孩子结点的标签 children = tree.findall(childtag) # 返回所有根目录孩子结点元素的列表 for child in children: # 遍历该列表 for i in range(len(child)): # 获取每个孩子结点元素的长度,然后遍历输出所有内容 print(child[i].tag + ':' + str(child[i].text)) print()