From XSLTC
Declare a prefix to point to a namespace URI. Inform SAX handler
if this is a new prefix mapping.
338525
protected boolean pushNamespace(String prefix, String uri)
    {
        try
        {
            if (m_prefixMap.pushNamespace(
                prefix, uri, m_elemContext.m_currentElemDepth))
            {
                startPrefixMapping(prefix, uri);
                return true;
            }
        }
        catch (SAXException e)
        {
            // falls through
        }
        return false;
    }
824657
@Override
    public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
        if ((defaultNamespace!=null) && (namespaceUri.equals(defaultNamespace))) {
            return "";
        }

        if (namespaceUri.equals(PROV_NS)) {
            return "prov";
        }
        if (namespaceUri.equals(PRINTER_NS)) {
            return "prn";
        }
   //     if (namespaceUri.equals(XSD_NS)) {
   //         return "xsd";
   //     }
        if (namespaceUri.equals(DOMProcessing.XSD_NS_FOR_XML)) { // TODO: TO CHECK that's the one we need
            return "xsd";
        }
        if (namespaceUri.equals(XML_NS)) {
            return "xml";
        }
        if (namespaceUri.equals(XSI_NS)) {
            return "xsi";
        }
        for (String k: nss.keySet()) {
            if (nss.get(k).equals(namespaceUri)) {
                return k;
            }
        }
        return suggestion;
    }
762465
public void setDefaultNamespaceURI(String namespaceURI) {
    if (namespaceURI == null)
      throw new IllegalArgumentException("Cannot set default prefix to null namespace URI");

    bindings.put(XMLConstants.DEFAULT_NS_PREFIX, namespaceURI);
  }
634144
@SuppressWarnings("unused")
	public void setPrefix(String prefix, String namespace) throws IOException {
		if (startTagIncomplete)
			closeStartTag();
		// assert prefix != null;
		// assert namespace != null;
		if (prefix == null) {
			prefix = "";
		}
		if (!namesInterned) {
			prefix = prefix.intern(); // will throw NPE if prefix==null
		} else if (checkNamesInterned) {
			checkInterning(prefix);
		} else if (prefix == null) {
			throw new IllegalArgumentException("prefix must be not null" + getLocation());
		}

		// check that prefix is not duplicated ...
		for (int i = elNamespaceCount[depth]; i < namespaceEnd; i++) {
			if (prefix == namespacePrefix[i]) {
				throw new IllegalStateException("duplicated prefix " + printable(prefix) + getLocation());
			}
		}

		if (!namesInterned) {
			namespace = namespace.intern();
		} else if (checkNamesInterned) {
			checkInterning(namespace);
		} else if (namespace == null) {
			throw new IllegalArgumentException("namespace must be not null" + getLocation());
		}

		if (namespaceEnd >= namespacePrefix.length) {
			ensureNamespacesCapacity();
		}
		namespacePrefix[namespaceEnd] = prefix;
		namespaceUri[namespaceEnd] = namespace;
		++namespaceEnd;
		setPrefixCalled = true;
	}
855049
def __add_namespaceinfo(self, ni):
        """"""
        self.__ns_uri_map[ni.uri] = ni
        for prefix in ni.prefixes:
            self.__prefix_map[prefix] = ni
219932
public void setNamespaceURI(String prefix, String namespaceURI) {
    if (prefix == null)
      throw new IllegalArgumentException("Cannot bind null prefix");
    if (namespaceURI == null)
      throw new IllegalArgumentException("Cannot set prefix to null namespace URI");

    // no need to store
    if (XMLConstants.XML_NS_PREFIX.equals(prefix) || XMLConstants.XMLNS_ATTRIBUTE.equals(prefix))
      return;

    bindings.put(prefix, namespaceURI);
  }
210197
def apply_namespace(qname, apply_prefix, apply_uri)
      local_part, prefix, uri = qname
      
      if !prefix
        prefix = apply_prefix
        uri = apply_uri
      end

      [local_part, prefix, uri].compact
    end
346142
def namespace(self, prefix=None):
        
        ns = self.schema.tns
        if ns[0] is None:
            ns = (prefix, ns[1])
        return ns
422603
@Override
  public String getPrefix(String namespaceURI) {
    // per javax.xml.namespace.NamespaceContext doc
    if (namespaceURI == null)
      throw new IllegalArgumentException("Cannot find prefix for null namespace URI");
    if (XMLConstants.XML_NS_URI.equals(namespaceURI))
      return XMLConstants.XML_NS_PREFIX;
    if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI))
      return XMLConstants.XMLNS_ATTRIBUTE;

    for (Map.Entry<String, String> entry: bindings.entrySet()) {
      if (namespaceURI.equals(entry.getValue()))
        return entry.getKey();
    }

    return null;
  }
655405
def _create_xml_node(tag, prefix=None, ns=None):
    """"""
    if prefix and ns:
        ET.register_namespace(prefix, ns)
    if ns:
        return ET.Element("{"+ns+"}"+tag)
    else:
        return ET.Element(tag)
1224611
private void addNamespace(String prefix, String uri) {
        prefixToURI.put(prefix, uri);
        uriToPrefix.put(uri, prefix);
    }
848799
private void initNamespaces()
    {
        // The initial prefix mappings will never be deleted because they are at element depth -1
        // (a kludge)

        // Define the default namespace (initially maps to "" uri)
        Stack stack;
        MappingRecord nn;
        nn = new MappingRecord(EMPTYSTRING, EMPTYSTRING, -1);
        stack = createPrefixStack(EMPTYSTRING);
        stack.push(nn);

        // define "xml" namespace
        nn = new MappingRecord(XML_PREFIX, "http://www.w3.org/XML/1998/namespace", -1);
        stack = createPrefixStack(XML_PREFIX);
        stack.push(nn);
    }
467874
public T namespace(String prefix, String namespaceUri) {
        getXpathVariableExtractor().getNamespaces().put(prefix, namespaceUri);
        xmlMessageValidationContext.getNamespaces().put(prefix, namespaceUri);
        return self;
    }
178903
protected void fixupElementNS(Node node) throws SAXException {
        String namespaceURI = ((Element) node).getNamespaceURI();
        String prefix = ((Element) node).getPrefix();
        String localName = ((Element) node).getLocalName();

        if (namespaceURI != null) {
            //if ( Element's prefix/namespace pair (or default namespace,
            // if no prefix) are within the scope of a binding )
            prefix = prefix == null ? "" : prefix;
            String inScopeNamespaceURI = fNSBinder.getURI(prefix);

            if ((inScopeNamespaceURI != null
                && inScopeNamespaceURI.equals(namespaceURI))) {
                // do nothing, declaration in scope is inherited
                
            } else {
                // Create a local namespace declaration attr for this namespace,
                // with Element's current prefix (or a default namespace, if
                // no prefix). If there's a conflicting local declaration
                // already present, change its value to use this namespace.
                
                // Add the xmlns declaration attribute
            	//fNSBinder.pushNamespace(prefix, namespaceURI, fElementDepth);
                if ((fFeatures & NAMESPACEDECLS) != 0) {
                    if ("".equals(prefix) || "".equals(namespaceURI)) {
                    	((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX, namespaceURI);
                    } else {
                    	((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX + ":" + prefix, namespaceURI);
                    }
                }
                fLocalNSBinder.declarePrefix(prefix, namespaceURI);
                fNSBinder.declarePrefix(prefix, namespaceURI);

            } 
        } else {
            // Element has no namespace
            // DOM Level 1
            if (localName == null || "".equals(localName)) {
                //  DOM Level 1 node!
                String msg =
                    Utils.messages.createMessage(
                        MsgKey.ER_NULL_LOCAL_ELEMENT_NAME,
                        new Object[] { node.getNodeName()});

                if (fErrorHandler != null) {
                    fErrorHandler.handleError(
                        new DOMErrorImpl(
                            DOMError.SEVERITY_ERROR,
                            msg,
                            MsgKey.ER_NULL_LOCAL_ELEMENT_NAME,
                            null,
                            null,
                            null));
                }
            } else {
            	namespaceURI = fNSBinder.getURI("");
            	if (namespaceURI !=null && namespaceURI.length() > 0) {
            	    ((Element)node).setAttributeNS(XMLNS_URI, XMLNS_PREFIX, "");
            		fLocalNSBinder.declarePrefix("", "");
                    fNSBinder.declarePrefix("", "");
            	}
            }
        }
    }
85914
private void setupXMLReader ()
    throws SAXException
    {
    xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    try {
        xmlReader.setFeature("http://xml.org/sax/features/namespaces",
                             false);
    } catch (SAXException e) {
        // NO OP: it's just extra information, and we can ignore it
    }
    xmlReader.setContentHandler(this);
    }
503915
public int resolveAndValidateElement()
        throws XMLStreamException
    {
        if (mDepth == 0) { // just a simple sanity check
            throw new IllegalStateException("Calling validate() on empty stack.");
        }
        AttributeCollector ac = mAttrCollector;

        // Any namespace declarations?
        {
            int nsCount = ac.getNsCount();
            if (nsCount > 0) {
                /* let's first invalidate old (possibly) shared ns ctxt too,
                 * if we had one; new one can be created at a later point
                 */
                mLastNsContext = null;

                boolean internNsUris = mConfig.willInternNsURIs();
                for (int i = 0; i < nsCount; ++i) {
                    Attribute ns = ac.resolveNamespaceDecl(i, internNsUris);
                    String nsUri = ns.mNamespaceURI;
                    // note: for namespaces, prefix is stored as local name
                    String prefix = ns.mLocalName;

                    /* 18-Jul-2004, TSa: Need to check that 'xml' and 'xmlns'
                     *   prefixes are not re-defined (and 'xmlns' not even
                     *   defined to its correct ns).
                     */
                    if (prefix == "xmlns") {
                        // xmlns can never be declared, even to its correct URI
                        mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS);
                    } else if (prefix == "xml") {
                        // whereas xml is ok, as long as it's same URI:
                        if (!nsUri.equals(XMLConstants.XML_NS_URI)) {
                            mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML,
                                                      nsUri, null);
                        }
                        /* 09-Feb-2006, TSa: Hmmh. Now, should this explicit
                         *   xml declaration be visible to the app? SAX API
                         *   seem to ignore it.
                         */
                        //mNamespaces.addStrings(prefix, nsUri);
                    } else { // ok, valid prefix, so far
                        /* 17-Mar-2006, TSa: Unbinding default NS needs to
                         *    result in null being added:
                         */
                        if (nsUri == null || nsUri.length() == 0) {
                            nsUri = XmlConsts.DEFAULT_NAMESPACE_URI;
                        }
                        // The default ns binding needs special handling:
                        if (prefix == null) {
                            mCurrElement.mDefaultNsURI = nsUri;
                        }

                        /* But then let's ensure that URIs matching xml
                         * and xmlns are not being bound to anything else
                         */
                        if (internNsUris) { // identity comparison is ok:
                            if (nsUri == XMLConstants.XML_NS_URI) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML_URI, prefix, null);
                            } else if (nsUri == XMLConstants.XMLNS_ATTRIBUTE_NS_URI) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS_URI);
                            }
                        } else { // need to check equals()
                            if (nsUri.equals(XMLConstants.XML_NS_URI)) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML_URI, prefix, null);
                            } else if (nsUri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS_URI);
                            }
                        }
                        /* and at any rate, binding needs to be added, to
                         * be visible to the app (including def ns):
                         */
                        mNamespaces.addStrings(prefix, nsUri);
                    }
                }
            }
        }

        /* 20-Feb-2006, TSa: Any attribute defaults for namespace declaration
         *   pseudo-attributes?
         */
        if (mMayHaveNsDefaults) {
            mNsDefaultProvider.checkNsDefaults(this);
        }

        // Then, let's set element's namespace, if any:
        String prefix = mCurrElement.mPrefix;
        String ns;

        if (prefix == null) { // use default NS, if any
            ns = mCurrElement.mDefaultNsURI;
        } else if (prefix == "xml") {
            ns = XMLConstants.XML_NS_URI;
        } else {
            // Need to find namespace with the prefix:
            ns = mNamespaces.findLastFromMap(prefix);
            /* 07-Sep-2007, TSa: "no namespace" should now be indicated
             *   by an empty string, however, due to historical reasons
             *   let's be bit defensive and allow nulls for the same too
             */
            if (ns == null || ns.length() == 0) {
                mReporter.throwParseError(ErrorConsts.ERR_NS_UNDECLARED, prefix, null);
            }
        }
        mCurrElement.mNamespaceURI = ns;

        // And finally, resolve attributes' namespaces too:
        int xmlidIx = ac.resolveNamespaces(mReporter, mNamespaces);
        mIdAttrIndex = xmlidIx;

        XMLValidator vld = mValidator;
        /* If we have no validator(s), nothing more to do,
         * except perhaps little bit of Xml:id handling:
         */
        if (vld == null) { // no validator in use
            if (xmlidIx >= 0) { // need to normalize xml:id, still?
                ac.normalizeSpacesInValue(xmlidIx);
            }
            return XMLValidator.CONTENT_ALLOW_ANY_TEXT;
        }

        // Otherwise need to call relevant validation methods.

        /* First, a call to check if the element itself may be acceptable
         * within structure:
         */
        vld.validateElementStart
            (mCurrElement.mLocalName, mCurrElement.mNamespaceURI, mCurrElement.mPrefix);

        // Then attributes, if any:
        int attrLen = ac.getCount();
        if (attrLen > 0) {
            for (int i = 0; i < attrLen; ++i) {
                ac.validateAttribute(i, mValidator);
            }
        }

        /* And finally let's wrap things up to see what textual content
         * is allowed as child content, if any:
         */
        return mValidator.validateElementAndAttributes();
    }
805191
public void add(String prefix, String uri) {
        if (uri == null) {
            namespaces.remove(prefix);
        } else {
            if (namespaces.containsKey(prefix)) {
                String currentUri = namespaces.get(prefix);
                if (!currentUri.equals(uri)) {
                    throw new FitFailureException(
                                String.format("The prefix %s is already mapped to %s",
                                                prefix, currentUri));
                }
            } else {
                namespaces.put(prefix, uri);
            }
        }
    }