# CS 2316, Writing XML example # #Import the module we want to use with a shorter name... import xml.etree.ElementTree as etree def xmlExport(filename): #The data we are exporting... students2316 = [ ('Jen', "A"), ("Robert", "B"), ("Bob", "C")] students1301 = [ ('Jay', "A"), ("Marcy", "B"), ("Will", "C")] #Our root xml element is a normal element object, but it is our #root because we will add all other elements to it as children. root = etree.Element("courses") root.text = "Jay's Courses" #a subelement of our root. We will create it now, and #append it to the root element later on in the code... cs2316 = etree.Element("CS2316", num_students="168" ) cs2316.text = "Data Manipulation" #We add student elements as subelements to our main element... for stInfo in students2316: etree.SubElement(cs2316, "student", grade=stInfo[1], name = stInfo[0]) root.append(cs2316) #We add the cs2316 element to the tree! #For the cs1301 element, we will create it as a SubElement of #the root, so we do not need to append it later... cs1301 = etree.SubElement(root, "cs1301", num_students="50") cs1301.text = "Introduction to Programming" for stInfo in students1301: s = etree.Element("student", grade=stInfo[1], name = stInfo[0]) cs1301.append(s) #Once we are done building our xml tree out of Element and SubElement #objects, we must create an ElementTree object to contain it. tree = etree.ElementTree(root) #The element tree knows how to write the data out to a text file # using xml to represent the tree of data in memory. It uses the # UTF-8 character encoding. ("UTF-8" is a good choice unless you know # you want to use a different encoding...) tree.write(filename, "UTF-8") xmlExport("test.xml") print("wrote data!")