Py002-02-06常用模块五(xml)

xml模块

你肯定见过如下文件 1.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 attr_test="yes">2009</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year attr_test="yes">2012</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year attr_test="yes">2012</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>

通过xml模块,获取data节点

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

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

# 第一步 获取 根节点
print(root.tag) # data

# 第二步 遍历子节点
for child in root:
# tag 节点名称 attrib 节点属性(字典形式)
print(child.tag,child.attrib)
for i in child:
# text 节点文本内容
print(i.tag,i.text)

# 只遍历指定节点 如只筛选 year节点
for node in root.iter('year'):
print(node.tag,node.text)

CRUD

  • 修改

还是刚才那个xml文件

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

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

# 第一步 获取 根节点
print(root.tag) # data

# 第二步 把year里的 文本内容递增 并设置属性 xxx="aaa"
for node in root.iter('year'):
new_year = int(node.text) + 1
node.text = str(new_year)
node.set('xxx','aaa')
# 第三步 写入文件(保存)
tree.write("1bak.xml")
  • 删除
1
2
3
4
5
6
7
8
9
10
import xml.etree.ElementTree as ET

tree = ET.parse("1.xml")
root = tree.getroot()
# findall 代表筛选所有的 xxx节点
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('1bak2.xml')
  • 创建一个xml文档形如以下格式
1
2
3
4
5
6
7
8
<?xml version='1.0' encoding='utf-8'?>
<namelist>
<userInfo info="3">
<name>hjx</name>
<age ageMax="1000" />
<sex>男</sex>
</userInfo>
</namelist>

创建一个xml的实现代码

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

# 根节点
root_node = ET.Element('namelist')

info = ET.SubElement(root_node,"userInfo",attrib={"info":"3"})
name = ET.SubElement(info,"name")
name.text = "hjx"
age = ET.SubElement(info,"age",attrib={"ageMax":"1000"})
sex = ET.SubElement(info,"sex")
sex.text = '男'

# 生成文档对象
et = ET.ElementTree(root_node)
et.write("userInfo.xml",encoding="utf-8",xml_declaration=True)