Next / Previous / Contents / Shipman's homepage

6.8. BirdNoteSet.writeFile(): Translate to XML

To create an XML representation of a BirdNoteSet, we rebuild the XML tree.

birdnotes.py
# - - -   B i r d N o t e S e t . w r i t e F i l e

    def writeFile ( self, fileName ):
        """Translate back to XML.
        """

First we create the root element, and then install that element as the root of an ElementTree instance that will contain the whole document.

birdnotes.py
        #-- 1 --
        # [ tree  :=  an et.ElementTree instance with root element
        #             rnc.NOTE_SET_N
        #   root  :=  that root element as an et.Element instance, with
        #             its rnc.PERIOD_A attribute set to self.period ]
        root  =  et.Element ( rnc.NOTE_SET_N )
        root.attrib[rnc.PERIOD_A]  =  self.period
        tree  =  et.ElementTree ( root )

Each of the DayNotes instances in this note-set will take care of adding the XML for itself and its subtree using its .writeNode() method.

birdnotes.py
        #-- 2 --
        # [ root  :=  root with content added for all DayNote
        #             instances in self ]
        for  dayNotes in self.genDays():
            dayNotes.writeNode ( root )

Finally, the ElementTree.write() method takes care of serializing itself into XML and writing that to the file of the given name.

birdnotes.py
        #-- 3 --
        # [ if fileName names a file that can be created new ->
        #     that file  :=  tree as XML
        #   else -> raise IOError ]
        tree.write ( fileName, pretty_print=True )