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

14.4. Document.splitQName(): Process a qualified name

This utility method is used to convert a qualified name into a namespace URI (if any) and a local name.

xml4create.py
# - - -   D o c u m e n t . s p l i t Q N a m e   - - -

    def splitQName ( self, qName ):
        """Translate a qualified name into (nsURI, localName)

          [ (self.nsMap is as invariant) and
            (qName is an XML qualified name) ->
              if qName has a namespace prefix ->
                if (self.nsMap is None) or
                (qName's namespace prefix is not a key in nsMap) ->
                  raise KeyError
                else ->
                  return (corresponding value from nsMap,
                  qName after the namespace prefix)
              else ->
                if None is a key in self.nsMap ->
                  return (None, qName)
                else ->
                  return (self.nsMap[None], qName) ]
        """

First we scan for a colon in the qName. If there isn't one, we're done.

xml4create.py
        #-- 1 --
        # [ if qName contains ":" ->
        #     prefix     :=  qName up to the first ":"
        #     localName  :=  qName after the first ":"
        #   else if self.nsMap has a key None ->
        #     return (self.nsMap[None], qName)
        #   else ->
        #     return (None, qName) ]
        firstColon  =  qName.find(":")
        if  firstColon < 0:
            if  self.nsMap:
                try:
                    nsuri  =  self.nsMap[None]
                except KeyError:
                    nsuri  =  None
            else:
                nsuri  =  None
            return (nsuri, qName)
        else:
            prefix     =  qName[:firstColon]
            localName  =  qName[firstColon+1:]

Next we look up the prefix in Document.nsMap. If self.nsMap isn't None, and that prefix is a key in self.nsMap, we return the namespace URI and local name.

xml4create.py
        #-- 2 --
        if self.nsMap is None:
            raise KeyError, ( "Document's root element '%s' had a "
                "namespace prefix, but no .nsMap was provided." )

        #-- 3 --
        # [ if prefix is a key in self.nsMap ->
        #     nsURI  :=  the corresponding value
        #   else -> raise KeyError ]
        nsURI  =  self.nsMap[prefix]

        #-- 3 --
        return (nsURI, localName)