xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
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> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
import xml.etree.ElementTree as ET tree = ET.parse("cccc.xml") #解释这个xml文件 root = tree.getroot() #获取该文件的跟节点 print(root.tag) #输出跟节点的标签 :data for child in root: #遍历跟节点的二级节点 print(child.tag,child.attrib) #打印出二级节点的标签名和属性:country {'name': 'Liechtenstein'} ... for i in child: #遍历二级节点的下一级节点 print(i.tag,i.text) #打印出该节点的标签名和文本:rank 5... for node in root.iter('year'): #只遍历year节点 print(node.tag,node.text) #打印出该节点的标签名和文本:year 2008... ###修改 for node in root.iter('year'): new_year = int(node.text)+1 #修改年份 node.text = str(new_year) #把修改好的数字转化为int node.set('updated','yes') #把属性设为'updated' ,值为‘yes' tree.write('cccc.xml') #写回到原文件 ###删除 for country in root.findall('country'): # 找出所有country标签 rank = int(country.find('rank').text) #找出country下的rank标签的文本 if rank > 50: #排名大于50 root.remove(country) #满足条件对象remove tree.write('output.xml') #删除完后生成新的文件 ###自己创建xml文档 new_xml = ET.Element("namelist") #创建跟节点 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) #参数分别是: (父节点对象,本节点名称,属性) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") sex.text = '33' #设置值 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = '19' et = ET.ElementTree(new_xml) #生成文档对象 et.write("test.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式 ''' 创建下xml文档如下: <namelist> <name enrolled="yes"> <age checked="no" /> <sex>33</sex> </name> <name enrolled="no"> <age>19</age> </name> </namelist> '''
删除后生成的新文件
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year updated="yes">2011</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated="yes">2014</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> </data>