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

14.8. Element.__init__()

This class wraps a DOM Element object in a more Pythonic class, so that the constructor both creates the new element and links it to its parent.

Normally, this constructor adds a new child element to an existing Element. However, it is also polymorphic: if called with a Document object as its first argument, instead of creating a new DOM Element, it wraps the document's root element.

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

    def __init__ ( self, parent, gi, **attrs ):
        """Constructor for Element.

          [ parent is an Element or DocumentFragment object ->
              parent  :=  parent with a new XML element appended
                  as its last or only child, having name=gi and
                  attributes=attrs
              return that new Element
            parent is a Document object ->
              parent  :=  parent with its .root attribute set to
                  a new Element object wrapping
                  parent.documentElement, and having
                  attributes=attrs ]
        """

First we eliminate the special case where parent is a Document.

xml4create.py
        #-- 1 --
        # [ if parent is a Document ->
        #     self.node  :=  parent.documentElement
        #   else 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=qName and attributes=attr
        #     self.node  :=  a new DOM Element object having
        #         the nsURI and localName inferred from
        #         self.doc.nsMap
        #   else -> raise KeyError ]
        if  parent.__class__ is Document:
            #-- 1.1 --
            # [ parent is a Document ->
            #     self.node  :=  parent.node.documentElement with
            #         attributes from attrs attached
            #     self.doc   :=  parent ]
            self.__wrapRoot ( parent, **attrs )
        else:
            #-- 1.2 --
            # [ 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 ]
            self.__newElement ( parent, gi, **attrs )