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

14.10. Element.__setAttr(): Set up one attribute

This method handles storing one attribute name/value pair in the DOM Element object.

xml4create.py
# - - -   E l e m e n t . _ _ s e t A t t r   - - -

    def __setAttr ( self, name, value ):
        """Store one XML attribute in a DOM Element.

          [ name and value are strings ->
              if name has a namespace prefix not defined
              in self.doc.nsMap ->
                raise KeyError
              else if name has a namespace prefix defined
              in self.doc.nsMap ->
                self.node  :=  self.node with a new Attribute
                    added having nsURI=self.doc.nsMap[attrName],
                    localName=(attrName past the first
                    colon, trailing underbar dropped if any),
                    and value=value
              else ->
                self.node  :=  self.node with a new Attribute
                    added having nsURI=None,
                    localName=(attrName, trailing underbar
                    dropped if any), and value=value ]
        """

First we have to check to see if the name has a namespace prefix. If so, we translate it to a namespace URI; if there is no prefix, the nsURI will be set to None.

xml4create.py
        #-- 1 --
        # [ if name has a namespace prefix ->
        #     if that prefix is not a key in self.doc.nsMap ->
        #       raise KeyError
        #     else ->
        #       nsUri      :=  the corresponding value
        #       localName  :=  name after the colon
        #   else ->
        #     nsUri      :=  None
        #     localName  :=  name ]
        nsUri, localName  =  self.doc.splitQName ( name )

Next we remove any trailing underbar from name.

xml4create.py
        #-- 2 --
        if  name[-1] == '_':
            name  =  name[:-1]

Now we have all we need to create the DOM Element.

xml4create.py
        #-- 3 --
        # [ self.node  :=  self.node with a new attribute added
        #       having nsURI=nsUri, name=name, and value=value ]
        self.node.setAttributeNS ( nsUri, name, value )