def xml2json_from_elementtree(el, preserve_whitespaces=False):
 res = {}
 if (el.tag[0] == '{'):
  (ns, name) = el.tag.rsplit('}', 1)
  res['tag'] = name
  res['namespace'] = ns[1:]
 else:
  res['tag'] = el.tag
 res['attrs'] = {}
 for (k, v) in el.items():
  res['attrs'][k] = v
 kids = []
 if (el.text and (preserve_whitespaces or (el.text.strip() != ''))):
  kids.append(el.text)
 for kid in el:
  kids.append(xml2json_from_elementtree(kid, preserve_whitespaces))
  if (kid.tail and (preserve_whitespaces or (kid.tail.strip() != ''))):
   kids.append(kid.tail)
 res['children'] = kids
 return res

def xml2json_from_elementtree ( el , preserve_whitespaces = False ) : res = { } if ( el . tag [ 0 ] == '{' ) : ( ns , name ) = el . tag . rsplit ( '}' , 1 ) res [ 'tag' ] = name res [ 'namespace' ] = ns [ 1 : ] else : res [ 'tag' ] = el . tag res [ 'attrs' ] = { } for ( k , v ) in el . items ( ) : res [ 'attrs' ] [ k ] = v kids = [ ] if ( el . text and ( preserve_whitespaces or ( el . text . strip ( ) != '' ) ) ) : kids . append ( el . text ) for kid in el : kids . append ( xml2json_from_elementtree ( kid , preserve_whitespaces ) ) if ( kid . tail and ( preserve_whitespaces or ( kid . tail . strip ( ) != '' ) ) ) : kids . append ( kid . tail ) res [ 'children' ] = kids return res
xml2json-direct simple and straightforward xml-to-json converter in python new bsd licensed URL .