Really simple way to deal with XML in Python?

前端 未结 9 1274
Happy的楠姐
Happy的楠姐 2020-12-04 22:36

Musing over a recently asked question, I started to wonder if there is a really simple way to deal with XML documents in Python. A pythonic way, if you will.

<
相关标签:
9条回答
  • 2020-12-04 23:02

    The suds project provides a Web Services client library that works almost exactly as you describe -- provide it a wsdl and then use factory methods to create the defined types (and process the responses too!).

    0 讨论(0)
  • 2020-12-04 23:04

    Take a look at Amara 2, particularly the Bindery part of this tutorial.

    It works in a way pretty similar to what you describe.

    On the other hand. ElementTree's find*() methods can give you 90% of that and are packaged with Python.

    0 讨论(0)
  • 2020-12-04 23:06

    You want a thin veneer? That's easy to cook up. Try the following trivial wrapper around ElementTree as a start:

    # geetree.py
    import xml.etree.ElementTree as ET
    
    class GeeElem(object):
        """Wrapper around an ElementTree element. a['foo'] gets the
           attribute foo, a.foo gets the first subelement foo."""
        def __init__(self, elem):
            self.etElem = elem
    
        def __getitem__(self, name):
            res = self._getattr(name)
            if res is None:
                raise AttributeError, "No attribute named '%s'" % name
            return res
    
        def __getattr__(self, name):
            res = self._getelem(name)
            if res is None:
                raise IndexError, "No element named '%s'" % name
            return res
    
        def _getelem(self, name):
            res = self.etElem.find(name)
            if res is None:
                return None
            return GeeElem(res)
    
        def _getattr(self, name):
            return self.etElem.get(name)
    
    class GeeTree(object):
        "Wrapper around an ElementTree."
        def __init__(self, fname):
            self.doc = ET.parse(fname)
    
        def __getattr__(self, name):
            if self.doc.getroot().tag != name:
                raise IndexError, "No element named '%s'" % name
            return GeeElem(self.doc.getroot())
    
        def getroot(self):
            return self.doc.getroot()
    

    You invoke it so:

    >>> import geetree
    >>> t = geetree.GeeTree('foo.xml')
    >>> t.xml_api_reply.weather.forecast_information.city['data']
    'Mountain View, CA'
    >>> t.xml_api_reply.weather.current_conditions.temp_f['data']
    '68'
    
    0 讨论(0)
提交回复
热议问题