Python获取任意xml节点值的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python获取任意xml节点值的方法。分享给大家供大家参考。具体实现方法如下:

# -*- coding: utf-8 -*-
import xml.dom.minidom
ELEMENT_NODE = xml.dom.Node.ELEMENT_NODE
class 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程序设计有所帮助。

相关文章

Python缓存技术实现过程详解

一段非常简单代码 普通调用方式 def console1(a, b): print("进入函数") return (a, b) print(console1(3, 'a...

浅谈Python的list中的选取范围

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。 Python有6个序列的内置类型,但最常见的是列表...

Python标准库使用OrderedDict类的实例讲解

目标:创建一个字典,记录几对python词语,使用OrderedDict类来写,并按顺序输出。 写完报错: [root@centos7 tmp]# python python_ter...

Python函数参数类型及排序原理总结

这篇文章主要介绍了Python函数参数类型及排序原理总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中函数的参数问题有...

Python numpy实现数组合并实例(vstack,hstack)

若干个数组可以沿不同的轴合合并到一起,vstack,hstack的简单用法, >>> a = np.floor(10*np.random.random((2,2))...