Python用来操作XML格式文档有两种方法,一种是Dom方式,将文档全部在内存中操作,然后导出到磁盘中,优点是操作方便,适合小文件,缺点是占用内存大;另外一种是Sax方式,采用的是一种流操作的模式,边读取,边解析,缺点是不方便解析,需要我们自己处理相关事件。
一般我们操作的xml文件不会太大,所以采用Dom方式是个不错的选择。
用下面的XML文件为例(test.xml):
<?xml version='1.0' encoding='UTF-8' ?>
<users>
<user id='1'>
<username>admin</username>
<email>admin@qq.com</email>
<age>23</age>
</user>
<user id='2'>
<username>user</username>
<email>user@qq.com</email>
<age>22</age>
</user>
</users>
0x01 解析XML
#/usr/bin/env python
#coding:utf-8
__author__='kikay'
'''
Dom方式读取XML格式文档
'''
import xml.dom.minidom as XmlDocument
#加载文件到内存
doc=XmlDocument.parse('test.xml')
#根节点users
xUsers=doc.getElementsByTagName('users')
if xUsers and len(xUsers)>0:
#读取user节点迭代式
xUserList=xUsers[0].getElementsByTagName('user')
for user in xUserList:
#读取属性id
id=user.attributes['id'].value
print 'user id: ',id
#读取用户名
xUsername=user.getElementsByTagName('username')
if xUsername and len(xUsername)>0:
username=xUsername[0].firstChild.data
print 'user name: ',username
#读取电子邮箱
xEmail=user.getElementsByTagName('email')
if xEmail and len(xEmail)>0:
email=xEmail[0].firstChild.data
print 'email: ',email
#读取年龄
xAge=user.getElementsByTagName('age')
if xAge and len(xAge)>0:
age=xAge[0].firstChild.data
print 'age: ',age
0x02 生成XML
#/usr/bin/env python
#coding:utf-8
__author__='kikay'
'''
XmlWriter.py: Dom方式生成XML格式文档
'''
import xml.dom.minidom as XmlDocument
#定义XML文档对象
doc=XmlDocument.Document()
#创建根节点
xUsers=doc.createElement('users')
doc.appendChild(xUsers)
#添加用户1
xUser=doc.createElement('user')
xUsers.appendChild(xUser)
xUser.attributes['id']='1'
xUsername=doc.createElement('username')
xUser.appendChild(xUsername)
xUsername.appendChild(doc.createTextNode('admin'))
xEmail=doc.createElement('email')
xUser.appendChild(xEmail)
xEmail.appendChild(doc.createTextNode('admin@qq.com'))
xAge=doc.createElement('age')
xUser.appendChild(xAge)
xAge.appendChild(doc.createTextNode('23'))
#添加用户2
xUser=doc.createElement('user')
xUsers.appendChild(xUser)
xUser.attributes['id']='2'
xUsername=doc.createElement('username')
xUser.appendChild(xUsername)
xUsername.appendChild(doc.createTextNode('user'))
xEmail=doc.createElement('email')
xUser.appendChild(xEmail)
xEmail.appendChild(doc.createTextNode('user@qq.com'))
xAge=doc.createElement('age')
xUser.appendChild(xAge)
xAge.appendChild(doc.createTextNode('22'))
#保存
with open('test.xml','w') as f:
f.write(doc.toxml(encoding='utf-8'))