python模块-xml、yaml

摘要

本文记录一些python中xml和yaml模块

xml

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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:

1
2
3
# print(root.iter('year')) #全文搜索
# print(root.find('country')) #在root的子节点找,只找一个
# print(root.findall('country')) #在root的子节点找,找所有
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import xml.etree.ElementTree as ET   #导入模块,名字太长了,把这个模块名重命名为ET

tree = ET.parse("xmltest.xml") #parse解析,用ET模块下的parse这个方法把xml文件解析开,解析开拿到一个tree,tree就是一个对象

root = tree.getroot() #这个对象可以调用方法,getroot就是根的意思
print(root.tag) #root这个对象有一个属性tag,tag的值就是根标签的名字
#遍历xml文档
for child in root:
print('========>',child.tag,child.attrib,child.attrib['name'])
for i in child:
print(i.tag,i.attrib,i.text)

#只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)
#---------------------------------------

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()

#修改
for node in root.iter('year'):
new_year=int(node.text)+1
node.text=str(new_year)
node.set('updated','yes')
node.set('version','1.0')
tree.write('test.xml')


#删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)

tree.write('output.xml')
1
2
3
4
5
6
7
8
9
10
11
12
13
#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall('country'):
for year in country.findall('year'):
if int(year.text) > 2000:
year2=ET.Element('year2')
year2.text='新年'
year2.attrib={'update':'yes'}
country.append(year2) #往country节点下添加子节点

tree.write('a.xml.swap')

自己创建xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import xml.etree.ElementTree as ET


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) #打印生成的格式

yaml

首先安装yaml模块

1
pip3 install pyyaml

编写yaml配置文件 yaml_example.yaml

1
2
3
4
5
6
7
8
9
10
 1 name: junxi
2 age: 18
3 spouse:
4 name: Rui
5 age: 18
6 children:
7 - name: Chen You
8 age: 3
9 - name: Ruo Xi
10 age: 2

编写解析yaml文件的python程序 yaml_example.py

1
2
3
4
5
6
7
8
9
1 import yaml
2
3 f = open('yaml_example.yaml')
4 content = yaml.load(f)
5 print(type(content))
6 print('before modification:', content)
7 content['age'] = 17
8 content['children'][1]['age'] = 1
9 print('after modification', content)

程序输出的结果为:

1
2
3
1 <type 'dict'>
2 ('before modification:', {'age': 18, 'spouse': {'age': 18, 'name': 'Rui'}, 'name': 'junxi', 'children': [{'age': 3, 'name': 'Chen You'}, {'age': 2, 'name': 'Ruo Xi'}]})
3 ('after modification', {'age': 17, 'spouse': {'age': 18, 'name': 'Rui'}, 'name': 'junxi', 'children': [{'age': 3, 'name': 'Chen You'}, {'age': 1, 'name': 'Ruo Xi'}]})
Donate