python中解析xml文件的模块用法,以及对模块封装的方法。
原文转自:http://www.jbxue.com/article/16586.html

有如下的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: www.jbxue.com
<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解析xml模块封装代码的更多相关文章

  1. python 解析XML python模块xml.dom解析xml实例代码

    分享下python中使用模块xml.dom解析xml文件的实例代码,学习下python解析xml文件的方法. 原文转自:http://www.jbxue.com/article/16587.html ...

  2. python解析xml之lxml

    虽然python解析xml的库很多,但是,由于lxml在底层是用C语言实现的,所以lxml在速度上有明显优势.除了速度上的优势,lxml在使用方面,易用性也非常好.这里将以下面的xml数据为例,介绍l ...

  3. python 解析xml

    在工作中很多时候都要用到xml,使用这个时候难免会设计到解析他,然后就研究了一下python解析xml问题,看了很多东西,python有很多解析xml的包,但是也折腾我好一段时间,最后选择了这个方法. ...

  4. 横向对比分析Python解析XML的四种方式

    横向对比分析Python解析XML的四种方式 在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜 ...

  5. python解析xml

    python解析xml import xml.dom.minidom as minidom dom = minidom.parse("aa.xml") root = dom.get ...

  6. Python 解析 XML 文件生成 HTML

    XML文件result.xml,内容如下: <ccm> <metric> <complexity>1</complexity> <unit> ...

  7. Python 解析XML实例(xml.sax)

    已知movies.xml <collection shelf="New Arrivals"> <movie title="Enemy Behind&qu ...

  8. 【TensorFlow】Python解析xml文件

    最近在项目中使用TensorFlow训练目标检测模型,在制作自己的数据集时使用了labelimg软件对图片进行标注,产生了VOC格式的数据,但标注生成的xml文件标签值难免会产生个别错误造成程序无法跑 ...

  9. PYTHON解析XML的多种方式效率对比实测

    在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜索后发现,目前应用比较广泛,且效率相对较高的E ...

随机推荐

  1. 使用mustache.js 模板引擎输出html

    看了https://mustache.github.io/你就知道mustache是非常强大的模板引擎,支持多种语言,下面是个简单入门例子: MVC Model public class Studen ...

  2. 关于asp.net 网站网站发布时提示:错误 27 对路径 AppData\Local\Temp\~632b\bin\App_Code.compil的解决方法

    关于asp.net 网站网站发布时提示:错误 27 对路径 AppData\Local\Temp\~632b\bin\App_Code.compil的解决方法 问题如下图所示,方法是去掉: <i ...

  3. 倍增法lca

    ][N],siz[N];//rt数组需要在dfs之前置-1. void dfs(int pos,int deep){ dep[pos]=deep; siz[pos]=; for(edge *it=ad ...

  4. C++编译错误syntax error : identifier 'THIS_FILE' 解决方法

    你到代码里搜索 THIS_FILE看是不是它定义在别的头文件前面了,如果是,把它们的头文件紧跟到Stdafx.h后面 我遇到过这问题,这样搞定的 今天遇到个编译错误:..\vc98\include\n ...

  5. windows7环境下svn服务器的配置及使用

    一.安装 1 软件准备: Setup-Subversion-1.7.8 TortoiseSVN-1.7.11.23600-win32-svn-1.7.8 2 安装: 安装个人的需要设定好安装路径. 3 ...

  6. Android设置透明、半透明等效果

    设置透明效果 大概有三种 1.用android系统的透明效果Java代码 android:background="@android:color/transparent"  例如 设 ...

  7. C#数字图像处理算法学习笔记(三)--图像几何变换

    C#数字图像处理算法学习笔记(三)--图像几何变换 几何图像处理包括 图像的平移变换,镜像变换,旋转变换,伸缩变换,在这里仅以水平镜像为例,通过代码来理解其基本操作方式: 翻转前:

  8. im4java开发向导

    0.搜索ImageMagick下载安装 1.Setting up the Environment    引入im4java到classpath    设置图片处理引擎的command searchpa ...

  9. 慕课网-安卓工程师初养成-2-12 如何在Java中使用注释

    来源:http://www.imooc.com/code/1274 在编写程序时,经常需要添加一些注释,用以描述某段代码的作用. 一般来说,对于一份规范的程序源代码而言,注释应该占到源代码的 1/3 ...

  10. css显示出三角形

    其实非常简单,就是设置一个div 让div的宽度和高度都设置为0, 然后为div设置一个border 因为角部位,比如我设置border-left和border-top 角部分是各自占用一半, 所以当 ...