python解析xml模块封装代码


Posted in Python onFebruary 07, 2014

有如下的xml文件:

<?xml version="1.0" encoding="utf-8" ?>  
<root>  
<childs>  
<child name='first' >1</child>  
<child value="2">2</child>  
</childs>  
</root>

下面介绍python解析xml文件的几种方法,使用python模块实现。

方式1,python模块实现自动遍历所有节点:

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
from xml.sax.handler import ContentHandler  
from xml.sax import parse
class TestHandle(ContentHandler):  
    def __init__(self, inlist):  
        self.inlist = inlist      def startElement(self,name,attrs):  
        print 'name:',name, 'attrs:',attrs.keys()  
    def endElement(self,name):  
        print 'endname',name  
    def characters(self,chars):  
        print 'chars',chars  
        self.inlist.append(chars)  
              
if __name__ == '__main__':  
    lt = []  
    parse('test.xml', TestHandle(lt))  
    print lt

结果:
[html] view plaincopy
name: root attrs: [] 
chars  

name: childs attrs: [] 
chars  

name: child attrs: [u'name'] 
chars 1 
endname child 
chars  

name: child attrs: [u'value'] 
chars 2 
endname child 
chars  

endname childs 
chars  

endname root 
[u'\n', u'\n', u'1', u'\n', u'2', u'\n', u'\n']

方式2,python模块实现获取根节点,按需查找指定节点:

#!/usr/bin/env python    
# -*- coding: utf-8 -*-    
from xml.dom import minidom    
xmlstr = '''''<?xml version="1.0" encoding="UTF-8"?> 
<hash> 
    <request name='first'>/2/photos/square/type.xml</request> 
    <error_code>21301</error_code> 
    <error>auth faild!</error> 
</hash> 
'''  
def doxml(xmlstr):  
    dom = minidom.parseString(xmlstr)      
    print 'Dom:'      
    print dom.toxml()        root = dom.firstChild      
    print 'root:'      
    print root.toxml()    
    childs = root.childNodes    
    for child in childs:  
        print child.toxml()  
        if child.nodeType == child.TEXT_NODE:  
            pass  
        else:  
            print 'child node attribute name:', child.getAttribute('name')  
            print 'child node name:', child.nodeName  
            print 'child node len:',len(child.childNodes)  
            print 'child data:',child.childNodes[0].data  
            print '======================================='  
            print 'more help info to see:'  
            for med in dir(child):  
                print help(med)      
                
if __name__ == '__main__':    
    doxml(xmlstr)

结果:
[html] view plaincopy
Dom: 
<?xml version="1.0" ?><hash> 
    <request name="first">/2/photos/square/type.xml</request> 
    <error_code>21301</error_code> 
    <error>auth faild!</error> 
</hash> 
root: 
<hash> 
    <request name="first">/2/photos/square/type.xml</request> 
    <error_code>21301</error_code> 
    <error>auth faild!</error> 
</hash> 

<request name="first">/2/photos/square/type.xml</request> 
child node attribute name: first 
child node name: request 
child node len: 1 
child data: /2/photos/square/type.xml 
======================================= 
more help info to see: 
两种方法各有其优点,python的xml处理模块太多,目前只用到这2个。

=====补充分割线================
实际工作中发现python的mimidom无法解析其它编码的xml,只能解析utf-8的编码,而其xml文件的头部申明也必须是utf-8,为其它编码会报错误。
网上的解决办法都是替换xml文件头部的编码申明,然后转换编码为utf-8再用minidom解码,实际测试为可行,不过有点累赘的感觉。

本节是 python解析xml模块封装代码 的第二部分。
====写xml内容的分割线=========

#!\urs\bin\env python  
#encoding: utf-8  
from xml.dom import minidom  class xmlwrite:  
    def __init__(self, resultfile):  
        self.resultfile = resultfile  
        self.rootname = 'api'  
        self.__create_xml_dom()  
    def __create_xml_dom(self):  
        xmlimpl = minidom.getDOMImplementation()  
        self.dom = xmlimpl.createDocument(None, self.rootname, None)  
        self.root = self.dom.documentElement  
    def __get_spec_node(self, xpath):  
        patharr = xpath.split(r'/')  
        parentnode = self.root  
        exist = 1  
        for nodename in patharr:  
            if nodename.strip() == '':  
                continue  
            if not exist:  
                return None  
            spcindex = nodename.find('[')  
            if spcindex > -1:  
                index = int(nodename[spcindex+1:-1])  
            else:  
                index = 0  
            count = 0  
            childs = parentnode.childNodes  
            for child in childs:  
                if child.nodeName == nodename[:spcindex]:  
                    if count == index:  
                        parentnode = child  
                        exist = 1  
                        break  
                    count += 1  
                    continue  
                else:  
                    exist = 0  
        return parentnode  
          
    def write_node(self, parent, nodename, value, attribute=None, CDATA=False):  
        node = self.dom.createElement(nodename)  
        if value:  
            if CDATA:  
                nodedata = self.dom.createCDATASection(value)  
            else:  
                nodedata = self.dom.createTextNode(value)  
            node.appendChild(nodedata)  
            if attribute and isinstance(attribute, dict):  
                for key, value in attribute.items():  
                    node.setAttribute(key, value)     
        try:  
            parentnode = self.__get_spec_node(parent)  
        except:  
            print 'Get parent Node Fail, Use the Root as parent Node'  
            parentnode = self.root  
        parentnode.appendChild(node)  
      
    def write_start_time(self, time):  
        self.write_node('/','StartTime', time)  
    def write_end_time(self, time):  
        self.write_node('/','EndTime', time)      
    def write_pass_count(self, count):  
        self.write_node('/','PassCount', count)     
    def write_fail_count(self, count):  
        self.write_node('/','FailCount', count)     
    def write_case(self):  
        self.write_node('/','Case', None)     
    def write_case_no(self, index, value):  
        self.write_node('/Case[%s]/' % index,'No', value)  
    def write_case_url(self, index, value):  
        self.write_node('/Case[%s]/' % index,'URL', value)  
    def write_case_dbdata(self, index, value):  
        self.write_node('/Case[%s]/' % index,'DBData', value)  
    def write_case_apidata(self, index, value):  
        self.write_node('/Case[%s]/' % index,'APIData', value)  
    def write_case_dbsql(self, index, value):  
        self.write_node('/Case[%s]/' % index,'DBSQL', value, CDATA=True)  
    def write_case_apixpath(self, index, value):  
        self.write_node('/Case[%s]/' % index,'APIXPath', value)         
    def save_xml(self):  
        myfile = file(self.resultfile, 'w')  
        self.dom.writexml(myfile, encoding='utf-8')  
        myfile.close()  
if __name__ == '__main__':  
      xr = xmlwrite(r'D:\test.xml')  
      xr.write_start_time('2223')  
      xr.write_end_time('444')        
      xr.write_pass_count('22')  
      xr.write_fail_count('33')    
      xr.write_case()  
      xr.write_case()  
      xr.write_case_no(0, '0')  
      xr.write_case_url(0, 'http://www.google.com')     
      xr.write_case_url(0, 'http://www.google.com')     
      xr.write_case_dbsql(0, 'select * from ')  
      xr.write_case_dbdata(0, 'dbtata')  
      xr.write_case_apixpath(0, '/xpath')  
      xr.write_case_apidata(0, 'apidata')  
      xr.write_case_no(1, '1')         
      xr.write_case_url(1, 'http://www.baidu.com')     
      xr.write_case_url(1, 'http://www.baidu.com')     
      xr.write_case_dbsql(1, 'select 1 from ')  
      xr.write_case_dbdata(1, 'dbtata1')  
      xr.write_case_apixpath(1, '/xpath1')  
      xr.write_case_apidata(1, 'apidata1')  
      xr.save_xml()

以上封装了minidom,支持通过xpath来写节点,不支持xpath带属性的匹配,但支持带索引的匹配。
比如:/root/child[1], 表示root的第2个child节点。

Python 相关文章推荐
Python可跨平台实现获取按键的方法
Mar 05 Python
Python2.x版本中cmp()方法的使用教程
May 14 Python
在windows下快速搭建web.py开发框架方法
Apr 22 Python
Python标准模块--ContextManager上下文管理器的具体用法
Nov 27 Python
解决Ubuntu pip 安装 mysql-python包出错的问题
Jun 11 Python
Python 安装第三方库 pip install 安装慢安装不上的解决办法
Jun 18 Python
Python从文件中读取指定的行以及在文件指定位置写入
Sep 06 Python
解决Tensorflow占用GPU显存问题
Feb 03 Python
python去除删除数据中\u0000\u0001等unicode字符串的代码
Mar 06 Python
python3 中时间戳、时间、日期的转换和加减操作
Jul 14 Python
python Matplotlib基础--如何添加文本和标注
Jan 26 Python
Pytorch distributed 多卡并行载入模型操作
Jun 05 Python
python 解析XML python模块xml.dom解析xml实例代码
Feb 07 #Python
python合并文本文件示例
Feb 07 #Python
python实现哈希表
Feb 07 #Python
python处理cookie详解
Feb 07 #Python
urllib2自定义opener详解
Feb 07 #Python
python解析html开发库pyquery使用方法
Feb 07 #Python
python3.3实现乘法表示例
Feb 07 #Python
You might like
浅析php中常量,变量的作用域和生存周期
2013/08/10 PHP
关于扩展 Laravel 默认 Session 中间件导致的 Session 写入失效问题分析
2016/01/08 PHP
js String对象中常用方法小结(字符串操作)
2012/01/27 Javascript
JavaScript事件委托用法分析
2015/01/24 Javascript
基于JavaScript实现文字超出部分隐藏
2016/02/29 Javascript
基于Vue.js的表格分页组件
2016/05/22 Javascript
EasyUI中在表单提交之前进行验证
2016/07/19 Javascript
Bootstrap Search Suggest使用例子
2016/12/21 Javascript
浅谈vue-lazyload实现的详细过程
2017/08/22 Javascript
使用Vuex实现一个笔记应用的方法
2018/03/13 Javascript
使用jQuery给Table动态增加行、清空table的方法
2018/09/05 jQuery
vue swipe自定义组件实现轮播效果
2019/07/03 Javascript
vue点击当前路由高亮小案例
2019/09/26 Javascript
vue组件入门知识全梳理
2020/09/21 Javascript
Vue项目中使用mock.js的完整步骤
2021/01/12 Vue.js
[04:38]完美世界携手游戏风云打造 卡尔工作室饰品系统篇
2013/04/25 DOTA
[00:30]塑造者的传承礼包-戴泽“暗影之焰”套装展示视频
2014/04/04 DOTA
[05:46]DOTA2英雄梦之声_第18期_陈
2014/06/20 DOTA
[44:22]完美世界DOTA2联赛循环赛 FTD vs PXG BO2第一场 11.01
2020/11/02 DOTA
python爬虫 基于requests模块发起ajax的get请求实现解析
2019/08/20 Python
Python 通过正则表达式快速获取电影的下载地址
2020/08/17 Python
Python extract及contains方法代码实例
2020/09/11 Python
纯css3实现图片翻牌特效
2015/03/10 HTML / CSS
html5 canvas手势解锁源码分享
2020/01/07 HTML / CSS
Vision Directa智利眼镜网:框架眼镜、隐形眼镜和名牌太阳眼镜
2016/11/23 全球购物
仓库保管员岗位职责
2013/12/20 职场文书
军训心得体会
2013/12/31 职场文书
运动会开幕式邀请函
2014/02/03 职场文书
幼儿园五一活动方案
2014/02/07 职场文书
社区两委对照检查材料
2014/08/23 职场文书
党代会心得体会
2014/09/04 职场文书
群众路线对照检查剖析材料
2014/10/09 职场文书
2014年团支书工作总结
2014/11/14 职场文书
学生会自荐信
2019/05/16 职场文书
日本十大血腥动漫,那些被禁播的动漫盘点
2022/03/21 日漫
tree shaking对打包体积优化及作用
2022/07/07 Java/Android