################################################################################
# - Read an XML file into a list of dictionaries
# - Write a list of dictionaries into an XML file
################################################################################
import xml.etree.ElementTree as ET

### Read an XML file into a list of dictionaries ###############################
def readXML(filename):
    list = []

    try: 
        tree = ET.parse(filename)                           #read and parse XML file into a tree
        root = tree.getroot()                               #get the root element (top of tree) 
    except Exception as e:
        print(F"Error reading/parsing input file - {e}")
        return(list)

    #Debug: Navigate and print all XML elements
    '''                                                                 #debug only
    print("ROOT: ", root.tag)                                           #print the root tag
    for row in root:
        print("ROW: ", row.tag)                                         #print each row tag
        for elem in row:
            print(elem.tag +'='+ elem.text, elem.attrib, ' ', end='')   #print each element tag=content and attributes
        print()
    '''

    #Load XML tree into list of dictionaries
    for row in root:
        dict = {}
        for element in row :
            if not element.attrib: attributes = ""      #if attrib dictionary empty, attributes=''                          
            dict[element.tag] = element.text            #add element name/value pair to dictionary
        list.append(dict)                               #add entire dictionary into list    

    return(list)                                        #a list of dictionaries      


### Write a list of dictionaries into an XML file ##############################
def writeXML(list, filename):

    try:
        root = ET.Element('sqlData')                            #create the root element

        for dict in list:                                       #loop thru the list
            row = ET.SubElement(root,'row')                     #create a row element, & attach to root
            for (name,value) in dict.items():                   #loop thru the dictionary
                elem = ET.SubElement(row, name, attrib={})      #create an element, & attach to row. No attributes 
                elem.text = value                               #set the element content

        xml = ET.tostring(root)                                 #convert the tree object to bytes sequence
        xml = xml.decode()                                      #convert bytes sequence to a string

        xml = xml.replace('<row>',     '\n<row>\n    ')         #optional add newlines and indentation 
        xml = xml.replace('</row>',    '\n</row>')
        xml = xml.replace('</sqlData>','\n</sqlData>')
    except Exception as e:
        print(F"Error creating XML tree - {e}")
        return(False)
 
    try:
        with open(filename, "w") as xmlfile:                    #open file for write
            xmlfile.write(xml)                                  #write the xml to output file
    except Exception as e:
        print(F"Error writing to output file - {e}")
        return(False)
 
    return(True)
    

### main code (test only) ######################################################

#input_file  = '/users/samsu/desktop/students.xml'
#output_file = '/users/samsu/desktop/students2.xml'

#list  = readXML(input_file)
#is_ok = writeXML(list, output_file)