xml模块是一种文件数据处理格式的方法,常用与生成、解析或修改.xml配置文件
1.常见的.xml配置文件格式如下
<admin> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </admin>
2.xml模块的简单使用
# -*- coding:utf-8 -*- # Author:Wong Du import xml.etree.ElementTree as xet tree = xet.parse('test.xml') # 解析xml对象 root = tree.getroot() # 读取xml文件内容 # print(root.tag) #只显示第一层tag for i in root: print(i.tag, i.attrib) for i1 in i: print(i1.tag,i1.attrib,i1.text) for i in root.iter(): #获取所有层的tag print(i.tag) # 修改 root.tag = 'admin' tree.write('test.xml') # 删除 for i in root.iter(): if 'direction' in i.attrib: i.attrib.pop('direction') tree.write('test1.xml')
3. 用Python创建.xml文件小实例
# -*- coding:utf-8 -*- # Author:Wong Du import xml.etree.ElementTree as xet new_xml = xet.Element('Earth') Country = xet.SubElement(new_xml,'Country',attrib={'Cname':'China'}) Province = xet.SubElement(Country,'Province',attrib={'Pname':'Guangdong'}) Province2 = xet.SubElement(Country,'Province',attrib={'Pname':'Shanghai'}) Province3 = xet.SubElement(Country,'Province',attrib={'Pname':'Beijing'}) Province4 = xet.SubElement(Country,'Province',attrib={'Pname':'Guangxi'}) City = xet.SubElement(Province4,'City',attrib={'特色':'旅游'}) City.text = '桂林' xet_tree = xet.ElementTree(new_xml) xet_tree.write('create.xml',encoding='utf-8',xml_declaration=True) xet.dump(new_xml)
<?xml version='1.0' encoding='utf-8'?> <Earth> <Country Cname="China"> <Province Pname="Guangdong" /> <Province Pname="Shanghai" /> <Province Pname="Beijing" /> <Province Pname="Guangxi"> <City 特色="旅游">桂林</City> </Province> </Country> </Earth>