#CS 1803, Writing XML example # #Copyright Jay Summet import xml.etree.ElementTree as etree def xmlExport(filename): students1803 = [ ("Jen", "C"),("Robert", "B"), ("Sally", "A"), ("Bob","D") ] students1301 = [ ("Jay", "A"), ("Marcy", "B"), ("Will", "C"), ("Tom", "D") ] #First, build the root root = etree.Element("courses") #Create 1803 class with students, as it's own node, and then #later attach it to the root! cs1803 = etree.Element("cs1803", num_students=str(168)) for stInfo in students1803: student = etree.SubElement(cs1803, "student", grade=stInfo[1], name=stInfo[0]) #student.text = stInfo[0] #Attach as SubElement to root node! root.append(cs1803) #Create 1301 class with students, using SubElement of root! cs1301 = etree.SubElement(root,"cs1301", num_students=str(275)) for stInfo in students1301: student = etree.SubElement(cs1301, "student", grade=stInfo[1], name=stInfo[0] ) #studnet.text = stInfo[0] #Because cs1301 is already a subElement of the root ('courses') #we don't need to append it! #root.append(cs1301) tree = etree.ElementTree(root) #Finally, write the tree out! try: tree.write(filename,"UTF-8") print("Wrote the data out to:", filename) except err: print("Got an error!:", err) xmlExport("test.xml")