一、解析xmlspa
<?xml version="1.0"?> <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>
读取xml的两种方式:code
import xml.etree.ElementTree as ET # 一、从文件读取 tree = ET.parse('country_data.xml') root = tree.getroot() #二、 从字符串读取 root = ET.fromstring(country_data)
element对象的经常使用属性:xml
1. tag:string对象,表示标签内容。对象
2. attrib:dictionary对象,表示标签的属性。blog
3. text:string对象,表示element的内容。递归
4. tail:string对象,表示element闭合以后的尾迹。索引
获子节点的方式:element
# 一、使用循环 for child in root: print(child.tag, child.attrib) # 二、使用索引 root[0][1]
查找节点的经常使用APIrem
for neighbor in root.iter('neighbor'): print(neighbor.attrib) ''' 输出 {'name': 'Austria', 'direction': 'E'} {'name': 'Switzerland', 'direction': 'W'} {'name': 'Malaysia', 'direction': 'N'} {'name': 'Costa Rica', 'direction': 'W'} {'name': 'Colombia', 'direction': 'E'} '''
Element.find():只查找当前节点的直接子节点。
只查找当前节点的直接子节点,返回全部元素列表
节点的删除和修改文档
for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml')
<!--output.xml-->
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> </data>
二、新建一个xml文档
a = ET.Element('a') b = ET.SubElement(a,'b') c = ET.SubElement(a, 'c') d = ET.SubElement(c, 'd') ET.dump(a) # 输出:<a><b /><c><d /></c></a>