<s> """<STR_LIT>""" <EOL> import xml . dom . minidom <EOL> from collections import defaultdict <EOL> def xmltodict ( xmlstring ) : <EOL> """<STR_LIT>""" <EOL> doc = xml . dom . minidom . parseString ( xmlstring ) <EOL> return _elementtodict ( doc ) <EOL> def _elementtodict ( parent ) : <EOL> """<STR_LIT>""" <EOL> child = parent . firstChild <EOL> while child and child . nodeType == xml . dom . minidom . Node . TEXT_NODE and not child . data . strip ( ) : <EOL> child = child . nextSibling <EOL> if not child : <EOL> return None <EOL> if child . nodeType == xml . dom . minidom . Node . TEXT_NODE or child . nodeType == xml . dom . minidom . Node . CDATA_SECTION_NODE : <EOL> value = child . nodeValue <EOL> if value . isdigit ( ) : <EOL> value = int ( value ) <EOL> return value <EOL> d = defaultdict ( list ) <EOL> while child : <EOL> if child . nodeType == xml . dom . minidom . Node . ELEMENT_NODE : <EOL> attr_dict = { } <EOL> if child . hasAttributes ( ) : <EOL> attrs = child . attributes <EOL> for i in range ( <NUM_LIT:0> , attrs . length ) : <EOL> _attr = attrs . item ( i ) <EOL> attr_dict [ _attr . name ] = _attr . value <EOL> d [ child . tagName ] . append ( { '<STR_LIT>' : attr_dict , '<STR_LIT>' : _elementtodict ( child ) } ) <EOL> child = child . nextSibling <EOL> return dict ( d ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import json <EOL> import sys <EOL> try : <EOL> xml_file = sys . argv [ <NUM_LIT:1> ] <EOL> s = open ( xml_file , '<STR_LIT:r>' ) . read ( ) <EOL> except IndexError : <EOL> s = sys . stdin . read ( ) <EOL> d = xmltodict ( s ) <EOL> print ( json . dumps ( d , indent = <NUM_LIT:4> ) ) </s>
