Created
April 14, 2012 02:59
-
-
Save erynofwales/2381791 to your computer and use it in GitHub Desktop.
Small class to convert XML data to a dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from io import StringIO | |
from xml.etree.ElementTree import ElementTree, Element, parse, ParseError | |
class XMLDict(dict): | |
'''A dictionary-like object to represent XML data.''' | |
def __init__(self, xml=None): | |
'''Expects a string containing XML data.''' | |
try: | |
self.populate(parse(StringIO(unicode(xml))).getroot()) | |
except ParseError as pe: | |
raise TypeError('Invalid XML data: %s' % str(pe)) | |
except: | |
raise TypeError('Unparsable XML type: %s' % type(xml).__name__) | |
def populate(self, xml): | |
self._name = xml.tag | |
for attribute, value in xml.attrib.items(): | |
self[attribute] = value | |
self._text = '' if xml.text is None else xml.text.strip() | |
self._children = [] | |
for c in list(xml): | |
# Recurse | |
self.children.append(XMLDict(c)) | |
def __getattr__(self, key): | |
try: | |
return self[key] | |
except KeyError: | |
raise AttributeError("'%s' object has no attribute '%s'" % | |
(self.__class__.__name__, key)) | |
def __setattr__(self, key, value): | |
self[key] = value | |
def __str__(self): | |
return self._name | |
if __name__ == '__main__': | |
from pprint import pprint | |
xml = u''' | |
<container foo='a'> | |
<a> | |
<baz>some text</baz> | |
</a> | |
<b bar='attrib'>test string</b> | |
</container> | |
''' | |
o = XMLDict(xml) | |
pprint(o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment