Python is used to obtain any xml node value. python is used to obtain xml nodes.

Source: Internet
Author: User

Python is used to obtain any xml node value. python is used to obtain xml nodes.

This example describes how to obtain the value of any xml node using Python. Share it with you for your reference. The specific implementation method is as follows:

# -*- 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

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.