本文实例讲述了python获取任意xml节点值的方法。分享给大家供大家参考。具体实现方法如下:
# -*- coding: utf-8 -*-import xml.dom.minidomelement_node = xml.dom.node.element_nodeclass simplexmlgetter(object): def __init__(self, data): if type(data) == str: self.root = xml.dom.minidom.parse(data) else: self.root = data def __getattr__(self, name): #support . operation if name == 'data': return self.root.firstchild.data for c in self.root.childnodes: if c.nodetype == element_node and c.tagname == name: return simplexmlgetter(c) def __getitem__(self, index): #support [] operation enodes = [ e for e in self.root.parentnode.childnodes if e.nodetype == element_node and e.tagname == self.root.tagname] return simplexmlgetter(enodes[index]) def __call__(self, *args, **kwargs): #support () openration, for query conditions for e in self.root.parentnode.childnodes: if e.nodetype == element_node: for key in kwargs.keys(): if e.getattribute(key) != kwargs[key]: break else: return simplexmlgetter(e)if __name__ == __main__: x = simplexmlgetter(sysd.xml) print x.sysd.sysagent.param[2].data print x.sysd.sysagent.param(name=querytimeout, type=second).data
希望本文所述对大家的python程序设计有所帮助。