python - 常用模块 - xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,在以前,在json还没诞生之前,xml十分流行,

以至于到现在很多传统公司如金融行业的很多系统的接口还主要是xml。

 1 #!/usr/bin/env python
 2 #coding:utf-8
 3
 4
 5 import xml.etree.ElementTree as ET
 6
 7 print(‘‘‘
 8      =============打印根节点的名字============
 9     ‘‘‘)
10 tree = ET.parse("./file/test.xml")    #指定要解析的xml文件
11 root = tree.getroot()   #根节点里面的所有内容
12 print(root.tag)      #打印xml文件根节点的名字,eg:./file/test.xml中的data
13
14 print(‘‘‘
15      =============遍历整个xml文档============
16     ‘‘‘)
17 #遍历xml文档   .tag:节点名   .attrib: 节点属性   .text: 节点内容
18 for child in root:      #打印根节点下的第一层子节点 country
19     print(child.tag, child.attrib)
20     for i in child:      #打印第一层子节点下的子节点(第二层子节点)
21         print(i.tag,i.text)
22
23 print(‘‘‘
24      =============只遍历year 节点============
25     ‘‘‘)
26 #只遍历year 节点
27 # root.iter(‘year‘): 在./file/test.xml中选择出所有节点名为‘year‘的节点
28 # .iter(‘year‘)  返回一个迭代器包含所有匹配的元素。
29 for node in root.iter(‘year‘):
30     print(node.tag,node.text)
31
32 print(‘‘‘
33     =============修改xml文档============
34 ‘‘‘)
35 #修改xml文档,把所有year节点的值+1
36 for node in root.iter(‘year‘):
37     new_year = int(node.text) + 1
38     node.text = str(new_year)
39     node.set("updated","yes")    #给节点增加属性
40
41 tree.write("./file/test1.xml")   #对文档做修改后要进行写入,才能保存修改
42 print("修改结果看./file/test1.xml")
43
44 print(‘‘‘
45     =============删除xml文档节点============
46 ‘‘‘)
47 #删除指定node
48 #for country in root.iter(‘country‘):   可以有同样效果,原理不同
49 for country in root.findall(‘country‘):
50     print(country.tag,country.attrib)
51     rank = int(country.find(‘rank‘).text)
52     if rank > 50:
53         root.remove(country)
54
55 tree.write(‘./file/test2.xml‘)    #对文档做修改后要进行写入,才能保存修改
56 print("删除后的结果看./file/test1.xml")
57
58
59
60 print(‘=============创建xml文档============‘)
61
62 import xml.etree.ElementTree as ET
63
64 new_xml = ET.Element("namelist")  #定义根节点
65 name = ET.SubElement(new_xml,"name1",attrib={"enrolled":"yes"})
66 age = ET.SubElement(name,"age",attrib={"checked":"no"})
67 sex = ET.SubElement(name,"sex")
68 age.text = ‘33‘
69 sex.text = ‘male‘
70 name2 = ET.SubElement(new_xml,"name2",attrib={"enrolled":"no"})
71 age = ET.SubElement(name2,"age")
72 sex = ET.SubElement(name2,"sex")
73 age.text = ‘19‘
74 sex.text = ‘female‘
75
76 et = ET.ElementTree(new_xml) #生成文档对象
77 et.write("./file/test3.xml", encoding="utf-8",xml_declaration=True)
78
79 #ET.dump(new_xml) #打印生成的格式在屏幕
80
81 print(‘创建后结果看./file/test3.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>

test.xml

 1 <data>
 2     <country name="Liechtenstein">
 3         <rank updated="yes">2</rank>
 4         <year updated="yes">2009</year>
 5         <gdppc>141100</gdppc>
 6         <neighbor direction="E" name="Austria" />
 7         <neighbor direction="W" name="Switzerland" />
 8     </country>
 9     <country name="Singapore">
10         <rank updated="yes">5</rank>
11         <year updated="yes">2012</year>
12         <gdppc>59900</gdppc>
13         <neighbor direction="N" name="Malaysia" />
14     </country>
15     <country name="Panama">
16         <rank updated="yes">69</rank>
17         <year updated="yes">2012</year>
18         <gdppc>13600</gdppc>
19         <neighbor direction="W" name="Costa Rica" />
20         <neighbor direction="E" name="Colombia" />
21     </country>
22 </data>

test1.xml

 1 <data>
 2     <country name="Liechtenstein">
 3         <rank updated="yes">2</rank>
 4         <year updated="yes">2009</year>
 5         <gdppc>141100</gdppc>
 6         <neighbor direction="E" name="Austria" />
 7         <neighbor direction="W" name="Switzerland" />
 8     </country>
 9     <country name="Singapore">
10         <rank updated="yes">5</rank>
11         <year updated="yes">2012</year>
12         <gdppc>59900</gdppc>
13         <neighbor direction="N" name="Malaysia" />
14     </country>
15     </data>

test2.xml

1 <?xml version=‘1.0‘ encoding=‘utf-8‘?>
2 <namelist><name1 enrolled="yes"><age checked="no">33</age><sex>male</sex></name1><name2 enrolled="no"><age>19</age><sex>female</sex></name2></namelist>

test3.xml

时间: 2024-08-25 02:42:13

python - 常用模块 - xml处理模块的相关文章

Python常用的内建模块

PS:Python之所以自称“batteries included”,就是因为内置了许多非常有用的模块,无需额外安装和配置,即可直接使用.下面就来看看一些常用的内建模块. datetime dateime是Python中处理日期和时间的标准库. 获取当前日期和时间 原文地址:https://www.cnblogs.com/yunche/p/8999052.html

json,pickle,shelve模块,xml处理模块

常用模块学习-序列化模块详解 什么叫序列化? 序列化是指把内存里的数据类型转变成字符串,以使其能存储到硬盘或通过网络传输到远程,因为硬盘或网络传输时只能接受bytes. 为什么要序列化? 你打游戏过程中,打累了,停下来,关掉游戏.想过2天再玩,2天之后,游戏又从你上次停止的地方继续运行,你上次游戏的进度肯定保存在硬盘上了,是以何种形式呢?游戏过程中产生的很多临时数据是不规律的,可能在你关掉游戏时正好有10个列表,3个嵌套字典的数据集合在内存里,需要存下来?你如何存?把列表变成文件里的多行多列形式

python-day6-configparser模块,xml.etree模块

操作键值对文件 1 #文件db格式为 2 [section] 3 a = 1 4 b = 2 5 6 [section1] 7 d = 3 8 c = 4 9 10 import configparser 11 12 #获取所有节点 13 config = configparser.ConfigParser() 14 config.read('db') 15 ret = config.sections() 16 print(ret) 17 18 >>>['section', 'secti

python 常用模块 time random os模块 sys模块 json &amp; pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess logging re正则 转自老男孩老师Yuan:http://www.cnblogs.com/yuanchenqi/articles/5732581.html 模块&包(* * * * *) 模块(modue)的概念: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,

[python标准库]XML模块

1.什么是XML XML是可扩展标记语言(Extensible Markup Language)的缩写,其中的 标记(markup)是关键部分.您可以创建内容,然后使用限定标记标记它,从而使每个单词.短语或块成为可识别.可分类的信息. XML有以下几个特点. XML的设计宗旨是传输数据,而非显示数据. XML标签没有被预定义.您需要自行定义标签. XML被设计为具有自我描述性. XML是W3C的推荐标准. 其解析流程如下图: 2.常用解析XML的Python包 Python的标准库中,提供了6种

python常用模块-------转自林海峰老师

常用模块 一 time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行"type(time.time())",返回的是float类型. 格式化的时间字符串(Format String) 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时) 1 import tim

python_day06 常用模块xml/configparser/hashlib/subprocess 面向对象程序设计

常用模块shutilxmlconfigparserhashlibsuprocess面向对象的程序设计 常用模块 xml模块 1 <?xml version="1.0"?> 2 <data> 3 <country name="Liechtenstein"> 4 <rank updated="yes">2</rank> 5 <year>2008</year> 6 &l

Day05 - Python 常用模块

1. 模块简介 模块就是一个保存了 Python 代码的文件.模块能定义函数,类和变量.模块里也能包含可执行的代码. 模块也是 Python 对象,具有随机的名字属性用来绑定或引用. 下例是个简单的模块support.py 1 def print_func( par ): 2 print("Hello : ", par) 3 return 1)import 语句 想使用 Python 源文件,只需在另一个源文件里执行 import 语句,语法如下: import module1[, m

python 常用模块(转载)

转载地址:http://codeweblog.com/python-%e5%b8%b8%e7%94%a8%e6%a8%a1%e5%9d%97/ adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheetahcherrypy:一个WEB frameworkctypes:用来调用动态链接库DBUtils:数据库连接池django:一个WEB frameworkdocutils:用来写文档的dpkt:数据包的解包和组包My