Skip to content

Instantly share code, notes, and snippets.

@imlucas
Created May 28, 2009 03:54
Show Gist options
  • Select an option

  • Save imlucas/119082 to your computer and use it in GitHub Desktop.

Select an option

Save imlucas/119082 to your computer and use it in GitHub Desktop.
class Bag: pass
def unmarshal(element):
rc = Bag()
if isinstance(element, minidom.Element):
for key in element.attributes.keys():
setattr(rc, key, element.attributes[key].value)
childElements = [e for e in element.childNodes \
if isinstance(e, minidom.Element)]
if childElements:
for child in childElements:
key = child.tagName
if hasattr(rc, key):
if type(getattr(rc, key)) <> type([]):
setattr(rc, key, [getattr(rc, key)])
setattr(rc, key, getattr(rc, key) + [unmarshal(child)])
elif isinstance(child, minidom.Element) and \
(child.tagName == 'Details'):
# make the first Details element a key
setattr(rc,key,[unmarshal(child)])
#dbg: because otherwise 'hasattr' only tests
#dbg: on the second occurence: if there's a
#dbg: single return to a query, it's not a
#dbg: list. This module should always
#dbg: return a list of Details objects.
else:
setattr(rc, key, unmarshal(child))
else:
#jec: we'll have the main part of the element stored in .text
#jec: will break if tag <text> is also present
text = "".join([e.data for e in element.childNodes \
if isinstance(e, minidom.Text)])
setattr(rc, 'text', text)
return rc
from xml.dom import minidom
f = open('T:\guisettings.xml', 'r')
xml = unmarshal(minidom.parse(f.read()))
f.close()
print xml['weather']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment