Python获取任意xml节点值的方法
本文实例讲述了Python获取任意xml节点值的方法。分享给大家供大家参考。具体实现方法如下:
#-*-coding:utf-8-*-
importxml.dom.minidom
ELEMENT_NODE=xml.dom.Node.ELEMENT_NODE
classSimpleXmlGetter(object):
def__init__(self,data):
iftype(data)==str:
self.root=xml.dom.minidom.parse(data)
else:
self.root=data
def__getattr__(self,name):#support.operation
ifname=='data':
returnself.root.firstChild.data
forcinself.root.childNodes:
ifc.nodeType==ELEMENT_NODEandc.tagName==name:
returnSimpleXmlGetter(c)
def__getitem__(self,index):#support[]operation
eNodes=[eforeinself.root.parentNode.childNodes
ife.nodeType==ELEMENT_NODEande.tagName==self.root.tagName]
returnSimpleXmlGetter(eNodes[index])
def__call__(self,*args,**kwargs):#support()openration,forqueryconditions
foreinself.root.parentNode.childNodes:
ife.nodeType==ELEMENT_NODE:
forkeyinkwargs.keys():
ife.getAttribute(key)!=kwargs[key]:
break
else:
returnSimpleXmlGetter(e)
if__name__=="__main__":
x=SimpleXmlGetter("sysd.xml")
printx.sysd.sysagent.param[2].data
printx.sysd.sysagent.param(name="querytimeout",type="second").data
希望本文所述对大家的Python程序设计有所帮助。