<s> from xml . dom import minidom <EOL> from xml . etree import ElementTree as ET <EOL> import six <EOL> class XMLGeneratorElement ( object ) : <EOL> def __init__ ( self , name , parent , builder ) : <EOL> self . elem = ET . SubElement ( parent , name ) <EOL> self . parent = parent <EOL> self . builder = builder <EOL> self . prev_elem = None <EOL> def __enter__ ( self ) : <EOL> self . prev_elem = self . builder . curr_el <EOL> self . builder . curr_el = self . elem <EOL> def __exit__ ( self , * args ) : <EOL> self . builder . curr_el = self . prev_elem <EOL> self . prev_elem = None <EOL> def __getattr__ ( self , name ) : <EOL> return XMLGeneratorElement ( <EOL> name = name , <EOL> parent = self . elem , <EOL> builder = self . builder ) <EOL> def __call__ ( self , txt = None , ** kwargs ) : <EOL> kwargs = { k : str ( v ) for k , v in kwargs . items ( ) } <EOL> self . elem . attrib . update ( kwargs ) <EOL> if txt : <EOL> self . elem . text = str ( txt ) <EOL> return self <EOL> @ six . python_2_unicode_compatible <EOL> class XMLGenerator ( object ) : <EOL> def __init__ ( self , root_name , ** kwargs ) : <EOL> self . root = ET . Element ( root_name ) <EOL> kwargs = { k : str ( v ) for k , v in kwargs . items ( ) } <EOL> self . root . attrib . update ( kwargs ) <EOL> self . curr_el = self . root <EOL> def __getattr__ ( self , name ) : <EOL> return XMLGeneratorElement ( <EOL> name = name , <EOL> parent = self . curr_el , <EOL> builder = self ) <EOL> def __str__ ( self ) : <EOL> rough_string = ET . tostring ( self . root , encoding = '<STR_LIT:utf-8>' ) <EOL> reparsed = minidom . parseString ( rough_string ) <EOL> s = reparsed . toprettyxml ( indent = '<STR_LIT:U+0020>' , encoding = '<STR_LIT:utf-8>' ) <EOL> if six . PY2 : <EOL> return s <EOL> else : <EOL> return str ( s , encoding = '<STR_LIT:utf-8>' ) </s>
