Sunday, July 22, 2018

Python: convert XML to dictionary

#https://stackoverflow.com/questions/13101653/python-convert-complex-dictionary-of-strings-from-unicode-to-ascii
def convert(input):
    if isinstance(input, dict):
        return {convert(key): convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

#https://docs.python-guide.org/scenarios/xml/
import xmltodict
with open('sample.xml') as fd:
  doc = xmltodict.parse(fd.read())
#print(doc)

# doc is an ordered dict containing unicode. 

#https://stackoverflow.com/questions/3860813/recursively-traverse-multidimensional-dictionary-dimension-unknown
import pprint
#pprint.pprint(doc) # expects dict, not ordered dict

#https://stackoverflow.com/questions/20166749/how-to-convert-an-ordereddict-into-a-regular-dict-in-python3
import json
from collections import OrderedDict
output_dict = json.loads(json.dumps(doc))

# remove the unicode from keys and values
doc = convert(output_dict)

pprint.pprint(doc)

No comments:

Post a Comment