#!/usr/bin/python
#encoding:utf-8
from xml.dom import minidom
class xmlwrite:
def __init__(self, resultfile):
self.resultfile = resultfile
self.dom = minidom.parse(self.resultfile)
def get_node_with_xpath(self, xpath):
patharr = xpath.split(r'/')
parentnode = self.dom
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])
nodename = nodename[:spcindex]
else:
index = 0
count = 0
childs = parentnode.childNodes
for child in childs:
if child.nodeName == nodename:
if count == index:
parentnode = child
exist = 1
break
count += 1
continue
else:
exist = 0
if exist==1:
return parentnode
if __name__ == '__main__':
xr = xmlwrite(r'e:/test.xml')
xpath = u'/api/Case[1]/No'
node = xr.get_node_with_xpath(xpath)
if node:
print node.toprettyxml()
else:
print 'can\'t find with xpath:', xpath
通过xpath读取xml节点
原创
©著作权归作者所有:来自51CTO博客作者testqa_cn的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章