Physics Derivation Graph navigation Sign in

Python: convert XML to dictionary

Published 2018-07-22T14:56:00.001Z by Physics Derivation Graph

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')
        return input

import xmltodict
with open('sample.xml') as fd:
  doc = xmltodict.parse(

# doc is an ordered dict containing unicode. 

import pprint
#pprint.pprint(doc) # expects dict, not ordered dict

import json
from collections import OrderedDict
output_dict = json.loads(json.dumps(doc))

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