您的位置:首页 > 编程语言 > Python开发

通过xpath读取xml节点

2016-06-05 21:36 423 查看
#!/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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python xml xpath