通过xpath读取xml节点
发布时间:2020-12-16 08:36:20 所属栏目:百科 来源:网络整理
导读:#!/usr/bin/python#encoding:utf-8from xml.dom import minidomclass 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'/
#!/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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |