I'm trying to make a dict class to process an xml but get stuck, I really run out of ideas. If someone could guide on this subject would be great.
code developed so far:
class XMLResponse(dict):
def __init__(self, xml):
self.result = True
self.message = ''
pass
def __setattr__(self, name, val):
self[name] = val
def __getattr__(self, name):
if name in self:
return self[name]
return None
message="<?xml version="1.0"?>ToveJaniReminderDon't forget me this weekend!"
XMLResponse(message)
解决方案
You can make use of xmltodict module:
import xmltodict
message = """<?xml version="1.0"?>ToveJaniReminderDon't forget me this weekend!"""
print xmltodict.parse(message)['note']
which produces an OrderedDict:
OrderedDict([(u'to', u'Tove'), (u'from', u'Jani'), (u'heading', u'Reminder'), (u'body', u"Don't forget me this weekend!")])
which can be converted to dict if order doesn't matter:
print dict(xmltodict.parse(message)['note'])
Prints:
{u'body': u"Don't forget me this weekend!", u'to': u'Tove', u'from': u'Jani', u'heading': u'Reminder'}