前端之家收集整理的这篇文章主要介绍了
通过xpath读取xml节点,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#!/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
原文链接:https://www.f2er.com/xml/295148.html