<?xml version="1.0" encoding="UTF-8" ?> <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>
import xml.etree.ElementTree as ET tree = ET.parse("mm.xml") # 加载想要读取的文件 root = tree.getroot() # 获取根节点 print('tag:',root.tag) # .tag 节点标签名 print("attrib:",root.attrib) # .attrib 节点标签的属性,属性名和属性值是键值对形式,多个属性对用空格分隔 print("text:",root.text) # .text 节点标签的内容 node1 = root.find("country") # 查找节点 第一个 country print(node1.attrib) node2 = root.findall("country") # 查找该层所有节点 country print(node2) for node in node2: if node.attrib["name"] == "日本": # 找到属性名为日本的节点 root.remove(node) # 调用上该节点的父节点来删除 break tree.write("02.xml",encoding="utf-8") # 执行完毕写回文件 dict1 = {} for i in root: # 遍历根节点的子节点 (一级节点) print("tag:{},attrib:{},text:{}".format(i.tag,i.attrib,i.text)) value = [] for j in i: # 遍历一级节点的子节点(二级节点) print("tag:{},attrib:{},text:{}".format(j.tag,j.attrib,j.text)) for k in j: print("tag:{},attrib:{},text:{}".format(k.tag,k.attrib,k.text)) if j.text is None: value.append(j.attrib) else: value.append({j.tag:j.text}) dict1[i.attrib["name"]] = value print(dict1)