file handling midair=str(int(incident midair))airport xml etree elementtree subelement(element"airport"airport text incident airport strip(narrative xml etree elementtree subelement(element"narrative"narrative text incident narrative strip(root append(elementtree xml etree elementtree elementtree(rootwe begin by creating the root element (then we iterate over all the incident records for each one we create an element (to hold the data for the incidentand use keyword arguments to provide the attributes all the attributes must be textso we convert the datenumericand boolean data items accordingly we don' have to worry about escaping "&""(or about quotes in attribute values)since the element tree module (and the dom and sax modulesautomatically take care of these details each has two subelementsone holding the airport name and the other the narrative text when subelements are created we must provide the parent element and the tag name an element' read/write text attribute is used to hold its text once the has been created with all its attributes and its and subelementswe add the incident to the hierarchy' root (element at the end we have hierarchy of elements that contains all the incident record datawhich we then trivially convert into an element tree trytree write(filename"utf- "except environmenterror as errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false return true writing the xml to represent an entire element tree is simply matter of telling the tree to write itself to the given file using the given encoding up to now when we have specified an encoding we have almost always used the string "utf this works fine for python' built-in open(function which can accept wide range of encodings and variety of names for themsuch as "utf- ""utf ""utf- "and "utf but for xml files the encoding name can be only one of the official namesso "utf is not acceptablewhich is why we have used "utf- see www org/tr/ /rec-xml - /#nt-encodingdecl and www iana org/assignments/character-sets for information about xml encodings