Created
May 28, 2009 03:54
-
-
Save imlucas/119082 to your computer and use it in GitHub Desktop.
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
| 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