首页 > 编程语言 > 详细

Python__xml模块

时间:2017-08-13 14:54:13      阅读:150      评论:0      收藏:0      [点我收藏+]

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不错,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能使用xml。

xml的格式:就是通过<>节点来进行的。

技术分享
 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>
View Code

xml的一些基本操作!!

 1 #Author wangmengzhu
 2 import xml.etree.ElementTree as ET
 3 tree = ET.parse(a.xml)
 4 root = tree.getroot()
 5 for child in root:
 6     for i in child:
 7         print(i.tag,i.attrib,i.text)
 8 
 9 
10 
11 #查找element元素的三种方式
12 years = root.iter(year)
13 for i in years:##从根开始,扫描整个xml文档,找到所有
14     print(i)
15 
16 res1 = root.find(year)#谁来调用,就从谁下一层开始找,只找一个
17 print(res1)
18 
19 res2 = root.findall(country)#找到下一层的所有
20 print(res2)
21 
22 years = root.iter(year)#扫描整个文档树,找到year
23 for year in years:
24     year.text = str(int(year.text) + 1)
25     year.set(updata,yes)#在内存中改属性结构
26     year.set(version,1.0)
27 tree.write(a.xml)
28 
29 #删除
30 for country in root.iter(country):
31     print(country.tag)
32     rank = country.find(rank)
33     if int(rank.text) > 10:
34         country.remove(rank)
35 tree.write(a.xml)
36 
37 #增加节点
38 for country in root.iter(country):
39     e = ET.Element(egon)
40     e.text = hello
41     e.attrib = {age:18}
42     country.append(e)
43 tree.write(a.xml)

 

Python__xml模块

原文:http://www.cnblogs.com/wangmengzhu/p/7353391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!