#!/usr/bin/env python

from xml.etree import ElementTree
import pprint

compute_tail = False

class XmlFileToDict():
    def __init__(self, xml_file_path):
        self.xml_file_path = xml_file_path

    def open_and_parse_xml_file(self):
        with open(self.xml_file_path, 'rt') as f:
            tree = ElementTree.parse(f)
        return tree

    def dict_list(self, node):
            res = {}
            res[node.tag] = []
            self.xml_to_dict(node,res[node.tag])
            reply = {}
            if compute_tail:
                reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib,'tail':node.tail}
            else:
                reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib}
            
            return reply

    def xml_to_dict(self, node, res):
            rep = {}
            
            if len(node):
                    #n = 0
                    for n in list(node):
                            rep[node.tag] = []
                            value = self.xml_to_dict(n,rep[node.tag])
                            if len(n):
                                    if compute_tail:
                                        value = {'value':rep[node.tag],'attributes':n.attrib,'tail':n.tail}
                                    else:
                                        value = {'value':rep[node.tag],'attributes':n.attrib}
                                    res.append({n.tag:value})
                            else :
                                    
                                    res.append(rep[node.tag][0])
                            
            else:
                    
                    
                    value = {}
                    if compute_tail:
                        value = {'value':node.text,'attributes':node.attrib,'tail':node.tail}
                    else:
                        value = {'value':node.text,'attributes':node.attrib}
                    
                    res.append({node.tag:value})
            
            return 
                        
if __name__ == '__main__' :
    xml_file_path ='tmp.xml' 
    xml2dict = XmlFileToDict(xml_file_path)
    tree = xml2dict.open_and_parse_xml_file()
    xml_dict = xml2dict.dict_list(tree.getroot())
    pprint.pprint(xml_dict)
