py14-xml模块

xml模块:
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文件:
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
for child in root:
print(child)
for i in child:
print(i)


标签名
属性
内容
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
for child in root:
print(child)
for i in child:
print(i.tag,i.attrib,i.text)


查找element元素的三种方式:
从根查找扫描整个xml文档
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

years=root.iter('year')
for i in years:
print(i)

root.find() #谁来调,就从谁下一层开始找,只找一个
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

res1=root.find('country')
print(res1)


root.findall() #谁来调,就从下一层全部开始找
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

# res1=root.find('country')
# print(res1)

res2=root.findall('country')
print(res2)

 


练习:生成b.xml,更新year里面的年份 +1年
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

years=root.iter('year')
for year in years:
year.text=str(int(year.text)+1)
tree.write('b.xml')


修改xml里面year里面的年份+1年
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

years=root.iter('year')
for year in years:
year.text=str(int(year.text)+1)
tree.write('a.xml')

修改xml里面year里面的年份+1年,再添加属性
import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

years=root.iter('year')
for year in years:
year.text=str(int(year.text)+1)
year.set('updates','yes')
year.set('version','1.0')
tree.write('a.xml')


删除rank>10


import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
#删除
for county in root.iter('country'):
# print(county.tag)
rank=county.find('rank')
if int(rank.text) > 10:
county.remove(rank)
tree.write('a.xml')

 


增加:

import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()
#删除
# for county in root.iter('country'):
# # print(county.tag)
# rank=county.find('rank')
# if int(rank.text) > 10:
# county.remove(rank)
# tree.write('a.xml')
#增加节点
for county in root.iter('country'):
e=ET.Element('egon')
e.text='hello'
e.attrib={'age':'18'}
county.append(e)

tree.write('a.xml')

posted @ 2017-08-18 09:56  sysgit  阅读(251)  评论(0编辑  收藏  举报