Next / Previous / Contents / Shipman's homepage

7.7. BirdNoteSet.writeFile(): Translate to XML

To create an XML representation of a BirdNoteSet, we rebuild the XML tree.
# - - -   B i r d N o t e S e t . w r i t e F i l e

    def writeFile(self, fileName, byPhylo=False):
        """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.
        #-- 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. Also, just to set off each day's notes visually within the XML, we add a comment line before each one, consisting of sixty-four equal signs.
        #-- 2 --
        # [ root  :=  root with content added for all DayNote
        #             instances in self ]
        for  dayNotes in self.genDays():
            root.append(et.Comment('=' * 64))
            dayNotes.writeNode(root, byPhylo)

Finally, the ElementTree.write() method takes care of serializing itself into XML and writing that to the file of the given name.
        #-- 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)