Python学习总结笔记(1)--Dom XML操作

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'))
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值