which we ignore we always clear the self __text string when we get start tag because no text tags are nested in the aircraft incident xml file format we don' do any exception-handling in the incidentsaxhandler class if an exception occurs it will be passed up to the callerin this case the import_xml_sax(methodwhich will catch it and output suitable error message def endelement(selfname)if name ="incident"if len(self __data! raise incidenterror("missing data"incident incident(**self __dataself __incidents[incident report_idincident elif name in frozenset({"airport""narrative"})self __data[nameself __text strip(self __text "when an end tag is read the xml sax handler contenthandler endelement(method is called if we have reached the end of an incident we should have all the necessary dataso we create new incident object and add it to the incidents dictionary if we have reached the end of text elementwe add an item to the self __data dictionary with the text that has been accumulated so far at the end we clear the self __text string ready for its next use (strictly speakingwe don' have to clear itsince we clear it when we get start tagbut clearing it could make difference in some xml formatsfor examplewhere tags can be nested def characters(selftext)self __text +text when the sax parser reads text it calls the xml sax handler contenthandler characters(method there is no guarantee that this method will be called just once with all the textthe text might come in chunks this is why we simply use the method to accumulate textand actually put the text into the dictionary only when the relevant end tag is reached ( more efficient implementation would have self __text be list with the body of this method being self __text append(text)and with the other methods adapted accordingly using the sax api is very different from using element tree or dombut it is just as effective we can provide other handlersand can reimplement additional methods in the content handler to get as much control as we like the sax parser itself does not maintain any representation of the xml document--this makes sax ideal for reading xml into our own custom data collectionsand also means that there is no sax "documentto write out as xmlso for writing xml we must use one of the approaches described earlier in this section