Next / Previous / Contents / Shipman's homepage

10.5. Loc.writeNode(): Translate to XML

This method attaches a loc element to the given parent node.

birdnotes.py
# - - -   L o c . w r i t e N o d e

    def writeNode(self, parent):
        """Build a loc element and its subtree.
        """
        #-- 1 --
        # [ parent  :=  parent with a new rnc.LOC_N node added
        #   result  :=  that node ]
        result = et.SubElement(parent, rnc.LOC_N)

        #-- 2 --
        # [ result  :=  result with an rnc.CODE_A attribute added
        #       made from self.code and an rnc.NAME_A from self.name ]
        result.attrib[rnc.CODE_A] = self.code
        result.attrib[rnc.NAME_A] = self.name

Next, we'll add child nodes for the waypoints, if any. See Section 11.3, “Gps.writeNode(): Convert to XML”.

birdnotes.py
        #-- 3 --
        # [ if  self._gpsList is empty ->
        #     lastGpsNode  :=  None
        #   else ->
        #     result  :=  result with rnc.GPS_N children added,
        #                 made from self._gpsList
        #     lastGpsNode  :=  the last such child added ]
        lastGpsNode = None
        for  gps in self._gpsList:
            lastGpsNode = gps.writeNode(result)

Adding the text is a little tricky because of the way lxml handles text. If there are any gps children, lxml wants the text to be in the .tail attribute of the last child element. However, there may not be any gps children, in which case lastGps will be None; in this case, the text goes into the .text attribute of the loc node.

birdnotes.py
        #-- 4 --
        if  self.text:
            if  lastGpsNode is None:
                result.text = self.text
            else:
                lastGpsNode.tail = self.text

        #-- 5 --
        return result