1 import xml.sax 2 import xml.sax.handler 3 import pprint 4 5 6 class XMLHandler(xml.sax.handler.ContentHandler): 7 def __init__(self): 8 self.buffer = "" 9 self.mapping = {} 10 11 def startElement(self, name, attributes): 12 self.buffer = "" 13 14 def characters(self, data): 15 self.buffer += data 16 17 def endElement(self, name): 18 self.mapping[name] = self.buffer 19 20 def getDict(self): 21 return self.mapping 22 23 24 data = '<?xml version="1.0" encoding="UTF-8"?><note><to>World</to><from>Linvo</from><heading>Hi</heading><body>Hello World!</body></note>' 25 26 xh = XMLHandler() 27 xml.sax.parseString(data.encode(), xh) 28 ret = xh.getDict() 29 30 pprint.pprint(ret)