Next / Previous / Contents / TCC Help System / NM Tech homepage

14.11. Element.__newElement(): Element child of an element

This method handles the typical case where an element is being added as the child of an existing element.

xml4create.py
# - - -   E l e m e n t . _ _ n e w E l e m e n t   - - -

    def __newElement ( self, parent, gi, **attrs ):
        """Create an element child of an existing element.

          [ (parent is an Element) and
            (gi is a string) and
            (attrs is a dictionary or None) ->
              if gi is a valid qName in the context of
              self.doc.nsMap ->
                parent     :=  parent with a new XML element
                    appended as its last or only child, having
                    name=gi and attributes from attrs
                self.node  :=  a new DOM Element object having
                    the nsURI and localName inferred from
                    self.doc.nsMap
                self.doc   :=  parent.doc
              else -> raise KeyError ]
        """

First, we set up a back-link in self.doc so we can jump directly from any Element to the containing Document.

xml4create.py
        #-- 1 --
        self.doc  =  parent.doc

Next we translate the qualified name into a namespace URI and local name.

xml4create.py
        #-- 2 --
        # [ if gi is a qualified name in the context of
        #   self.doc.nsMap ->
        #     nsUri      :=  the namespace URI of gi in that context
        #     localName  :=  the local name of gi
        #   else -> raise KeyError ]
        nsUri, localName  =  self.doc.splitQName ( gi )

We now have everything we need to create the DOM Element node and append it as the next child of the parent.

xml4create.py
        #-- 3 --
        # [ self.node  :=  a DOM Element node with namespace
        #       URI=nsUri and name=name ]
        self.node  =  self.doc.node.createElementNS ( nsUri, gi )

        #-- 4 --
        # [ parent.node  :=  parent.node with self.node added as
        #       its last or only child ]
        parent.node.appendChild ( self.node )

Finally, we set up any XML attributes if they were supplied.

xml4create.py
        #-- 5 --
        # [ if attrs is None ->
        #     I
        #   else if attrs contains any namespace prefixes that are
        #   not keys in self.doc.nsMap ->
        #     raise KeyError
        #   else ->
        #     self.node  :=  self.node with attribute names
        #         (with trailing "_" removed if present) and
        #         corresponding values from attrs ]
        if  attrs:
            self.update ( attrs )