Python 创建XML

xml.dom.minidom模块实现创建一个XML文档。

创建XML的过程
1、内存数据产生
2、产生xml内存对象(也就是DOM树)
3、产生根对象
4、往根对象里加数据
5、把xml内存对象写到文件
下面是一个创建xml文档的简单实例:

import xml.dom.minidom

#在内存中创建一个空的文档
doc = xml.dom.minidom.Document()
#创建一个根节点Managers对象
root = doc.createElement('Managers')
#设置根节点的属性
root.setAttribute('company', 'xx科技')
root.setAttribute('address', '科技软件园')
#将根节点添加到文档对象中
doc.appendChild(root)

managerList = [{'name' : 'joy', 'age' : 27, 'sex' : '女'},
{'name' : 'tom', 'age' : 30, 'sex' : '男'},
{'name' : 'ruby', 'age' : 29, 'sex' : '女'}
]

for i in managerList :
nodeManager = doc.createElement('Manager')
nodeName = doc.createElement('name')
#给叶子节点name设置一个文本节点,用于显示文本内容
nodeName.appendChild(doc.createTextNode(str(i['name'])))

nodeAge = doc.createElement("age")
nodeAge.appendChild(doc.createTextNode(str(i["age"])))

nodeSex = doc.createElement("sex")
nodeSex.appendChild(doc.createTextNode(str(i["sex"])))

#将各叶子节点添加到父节点Manager中,
#最后将Manager添加到根节点Managers中
nodeManager.appendChild(nodeName)
nodeManager.appendChild(nodeAge)
nodeManager.appendChild(nodeSex)
root.appendChild(nodeManager)
#开始写xml文档
fp = open('c:\wcx\Manager.xml', 'w')
doc.writexml(fp, indent=' ', addindent=' ', newl=' ', encoding="utf-8")
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
39
执行结果:

<?xml version="1.0" encoding="utf-8"?>
<Managers address="科技软件园" company="xx科技">
<Manager>
<name>joy</name>
<age>27</age>
<sex>女</sex>
</Manager>
<Manager>
<name>tom</name>
<age>30</age>
<sex>男</sex>
</Manager>
<Manager>
<name>ruby</name>
<age>29</age>
<sex>女</sex>
</Manager>
</Managers>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
用Python自带的写xml文档的API去写,比较方便,后期容易维护。如果直接用打开文件的方式,一行一行的去写,比较费时,也难以维护。

xml.dom模块创建xml的部分API
minidom.Document()
创建一个空白xml文档树对象。
每个xml文档都是一个Document对象,代表着内存中的DOM树。

doc. createElement(tagName)
生成xml文档节点。参数表示要生成节点的名称。
如:(注意这里使用的例子都来自于上面创建xml文档的程序中,下同)
#创建一个根节点Managers对象
root = doc.createElement('Managers')
1
2
3
node.setAttribute(attname, value)
给节点添加属性值对(Attribute)。
参数说明:
attname :属性的名称
value :属性的值
如:
设置根节点的属性:

root.setAttribute('company', 'xx科技')
1
doc.createTextNode(data)
给叶子节点添加文本节点。如:

#给叶子节点name设置一个文本节点,用于显示文本内容
nodeName.appendChild(doc.createTextNode(str(i['name'])))
1
2
3
node.appendChild(node1)
将节点node1t添加到节点node下。如:

#将叶子节点nodeName添加到父节点nodeManager下
nodeManager.appendChild(nodeName)
1
2
3
doc. writexml()
函数原型:

writexml(writer, indent='', addindent='', newl='', encoding=None)
1
将内存中xml文档树写入文件中。
参数说明:
writer :要写的目标文件的文件对象。
indent :

fp = open('c:\Manager.xml', 'w')
doc.writexml(fp, indent='', addindent=' ', newl=' ', encoding="utf-8")
---------------------
作者:世界看我我看世界
来源:CSDN
原文:https://blog.csdn.net/seetheworld518/article/details/49535285
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/zhouzhou0/p/10525821.html