If possible, use getAttributeNodeNS and setAttributeNS.

NB: This method doesn't handle namespaces properly.
978555
public function getOrCreateAttributeNode($qname)
    {
        if ($attr = $this->getAttributeNode($qname)) return $attr;

        $attr = new PHPTAL_Dom_Attr($qname, "", null, 'UTF-8'); // FIXME: should find namespace and encoding
        $this->attribute_nodes[] = $attr;
        return $attr;
    }
1136163
function _VirtualDom_applyAttrsNS(domNode, nsAttrs)
{
	for (var key in nsAttrs)
	{
		var pair = nsAttrs[key];
		var namespace = pair.__namespace;
		var value = pair.__value;

		value
			? domNode.setAttributeNS(namespace, key, value)
			: domNode.removeAttributeNS(namespace, key);
	}
}
263676
void pushSpaceHandling(Attributes attrs)
    throws org.xml.sax.SAXParseException
  {    
    String value = attrs.getValue("xml:space");
    if(null == value)
    {
      m_spacePreserveStack.push(m_spacePreserveStack.peekOrFalse());
    }
    else if(value.equals("preserve"))
    {
      m_spacePreserveStack.push(true);
    }
    else if(value.equals("default"))
    {
      m_spacePreserveStack.push(false);
    }
    else
    {
      SAXSourceLocator locator = getLocator();
      ErrorListener handler = m_stylesheetProcessor.getErrorListener();
  
      try
      {
        handler.error(new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_ILLEGAL_XMLSPACE_VALUE, null), locator)); //"Illegal value for xml:space", locator));
      }
      catch (TransformerException te)
      {
        throw new org.xml.sax.SAXParseException(te.getMessage(), locator, te);
      }
      m_spacePreserveStack.push(m_spacePreserveStack.peek());
    }
  }
1307827
@Override
	public String getAttribute(String name) {
		final String sourceMethod = "getAttribute"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(AggregatorExtension.class.getName(), sourceMethod, new Object[]{name});
		}
		String result = attributes.getProperty(name);
		if (result != null && aggregator != null) {
			result = aggregator.substituteProps(result);
		}
		if (isTraceLogging) {
			log.exiting(AggregatorExtension.class.getName(), sourceMethod, result);
		}
		return result;
	}
510862
@SuppressWarnings("unchecked")
    public String[] getAttributeNames() {

        List<String> names = new ArrayList<String>();
        Enumeration<String> keys = attributes.keys();
        while (keys.hasMoreElements()) {
            names.add((String) keys.nextElement());
        }
        String results[] = new String[names.size()];
        for (int i = 0; i < results.length; i++) {
            results[i] = (String) names.get(i);
        }
        return (results);

    }
105096
def method_or_name(namespace, x):
    '''
    
    '''
    if not isinstance(x, str):
        return x

    if hasattr(namespace, x):
        return getattr(namespace, x)

    attrs = [y for y in dir(namespace) if not y.startswith('_')]
    msg = '''"%s" is not available in %s.
These attributes are available: %s.''' % (x, namespace.__name__, attrs)
    raise AttributeError(msg)
41243
private Properties getNamespaces(Node node)
   {
      Properties namespaces = new Properties();
      NamedNodeMap attributes = node.getAttributes();
      for (int i = 0; i < attributes.getLength(); i++)
      {
         Attr attribute = (Attr)attributes.item(i);
         if (attribute.getName().startsWith("xmlns:"))
         {
            namespaces.setProperty(attribute.getName().substring(6), attribute.getValue());
         }
      }
      return namespaces;
   }
1211930
function(node, tagNames, attributeName) {
			var i = tagNames.length;

			while(i--) {
				if(node.tagName.toLowerCase() === tagNames[i]) {
					var attrValue = this.getAttribute(node, attributeName);
					if(attrValue && attrValue !== '') {
						return attrValue;
					}
				}
			}
			return null;
		}
268555
public XMLSerializer attribute(String namespace, String name, String value) throws IOException {
		if (!startTagIncomplete) {
			throw new IllegalArgumentException("startTag() must be called before attribute()" + getLocation());
		}
		// assert setPrefixCalled == false;
		out.write(' ');
		//// assert namespace != null;
		if (namespace != null && namespace.length() > 0) {
			// namespace = namespace.intern();
			if (!namesInterned) {
				namespace = namespace.intern();
			} else if (checkNamesInterned) {
				checkInterning(namespace);
			}
			String prefix = getPrefix(namespace, false, true);
			// assert( prefix != null);
			// if(prefix.length() == 0) {
			if (prefix == null) {
				// needs to declare prefix to hold default namespace
				// NOTE: attributes such as a='b' are in NO namespace
				prefix = generatePrefix(namespace);
			}
			out.write(prefix);
			out.write(':');
			// if(prefix.length() > 0) {
			// out.write(prefix);
			// out.write(':');
			// }
		}
		// assert name != null;
		out.write(name);
		out.write('=');
		// assert value != null;
		out.write(attributeUseApostrophe ? '\'' : '"');
		writeAttributeValue(value, out);
		out.write(attributeUseApostrophe ? '\'' : '"');
		return this;
	}
237670
def element_for_attribute(name, namespace='')
      val = instance_values[name]
      return "" if val == nil
      "<%s:%s val='%s'/>" % [namespace, Axlsx::camel(name, false), val]
    end
1255691
private void checkAndAddDefaults(QName name, XMLAttributes atts) {
    List<RelaxNGDefaultValues.Attribute> def = defaults.getDefaultAttributes(
        name.localpart, name.uri);
    if (def != null) {
      for (RelaxNGDefaultValues.Attribute a : def) {
        //EXM-24143 it is possible that the namespace of the default attribute is empty
        //and the namespace of the attribute declared in the XMLAttributes is NULL.
        boolean alreadyDeclared = false;
        alreadyDeclared = atts.getIndex(a.namespace, a.localName) >= 0;
        if(! alreadyDeclared) {
          if("".equals(a.namespace)) {
            //Extra check with NULL Namespace
            alreadyDeclared = atts.getIndex(null, a.localName) >= 0;    
          }
        }
        
        if (! alreadyDeclared) {
          String prefix = null;
          String rawname = a.localName;
          if (a.namespace != null && a.namespace.length() > 0) {
            prefix = context.getPrefix(a.namespace);
            if (prefix == null) {
              for (int i = 0; i < atts.getLength(); i++) {
                String attname = atts.getQName(i);
                if (attname.startsWith("xmlns:")) {
                  if (a.namespace.equals(atts.getValue(i))) {
                    prefix = attname.substring(6);
                  }
                }
              }
            }

            if (prefix != null && prefix.length() > 0) {
              rawname = prefix + ":" + a.localName;
              // double check in case of no namespace aware parsers.
              // if we want to fully handle this case we may need further
              // processing.
              if (atts.getIndex(rawname) < 0) {
                QName attName = new QName(fSymbolTable.addSymbol(prefix),
                    fSymbolTable.addSymbol(a.localName), fSymbolTable.addSymbol(rawname),
                    fSymbolTable.addSymbol(a.namespace));
                atts.addAttribute(attName, "CDATA", a.value);
                int attrIndex = atts.getIndex(attName.uri, attName.localpart);
                atts.setSpecified(attrIndex, false);
              }
            } else {
              int k = 1;
              if(
                  //EXM-24494 Prefer this prefix
                  //See the implementation in: org.dita.dost.reader.MergeTopicParser.startElement(String, String, String, Attributes)
                  //If the file is a composite no attributes are copied from the root element.
                  "http://dita.oasis-open.org/architecture/2005/".equals(a.namespace)) {
                prefix = "ditaarch";
              } else {
              	prefix = "ns" + k;
              }
              while (context.getURI(prefix) != null
                  || atts.getValue("xmlns:" + prefix) != null) {
                k++;
                prefix = "ns" + k;
              }
              rawname = prefix + ":" + a.localName;

              QName attNs = new QName(fSymbolTable.addSymbol("xmlns"),
                  fSymbolTable.addSymbol(prefix), fSymbolTable.addSymbol("xmlns:" + prefix),
                  fSymbolTable.addSymbol("http://www.w3.org/2000/xmlns/"));
              atts.addAttribute(attNs, "CDATA", a.namespace);
              context.declarePrefix(prefix, a.namespace);

              QName attName = new QName(fSymbolTable.addSymbol(prefix),
                  fSymbolTable.addSymbol(a.localName), fSymbolTable.addSymbol(rawname),
                  fSymbolTable.addSymbol(a.namespace));
              atts.addAttribute(attName, "CDATA", a.value);
              int attrIndex = atts.getIndex(attName.uri, attName.localpart);
              atts.setSpecified(attrIndex, false);
            }
          } else {
            String attname = fSymbolTable.addSymbol(a.localName);
            QName attName = new QName(null, attname, attname, null);
            atts.addAttribute(attName, "CDATA", a.value);
            int attrIndex = atts.getIndex(attname);
            atts.setSpecified(attrIndex, false);
          }
        }
      }
    }
  }
714758
public static void addNSdeclarations(Element source, Element target)
            throws Exception {
        NamedNodeMap sourceAttributes = source.getAttributes();
        Attr attribute;
        String attributeName;
        for (int i = 0; i <= sourceAttributes.getLength() - 1; i++) {
            attribute = (Attr) sourceAttributes.item(i);
            attributeName = attribute.getName();
            if (attributeName.startsWith("xmlns")
                    && !attributeName.startsWith("xmlns:soap-env")) {
                // System.out.println("XMLNS:" +
                // attributeName+":"+attribute.getValue());
                target.setAttribute(attributeName, attribute.getValue());
            }
        }
    }
80702
def match_attribute_name(self, el, attr, prefix):
        """"""

        value = None
        if self.supports_namespaces():
            value = None
            # If we have not defined namespaces, we can't very well find them, so don't bother trying.
            if prefix:
                ns = self.namespaces.get(prefix)
                if ns is None and prefix != '*':
                    return None
            else:
                ns = None

            for k, v in self.iter_attributes(el):

                # Get attribute parts
                namespace, name = self.split_namespace(el, k)

                # Can't match a prefix attribute as we haven't specified one to match
                # Try to match it normally as a whole `p:a` as selector may be trying `p\:a`.
                if ns is None:
                    if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):
                        value = v
                        break
                    # Coverage is not finding this even though it is executed.
                    # Adding a print statement before this (and erasing coverage) causes coverage to find the line.
                    # Ignore the false positive message.
                    continue  # pragma: no cover

                # We can't match our desired prefix attribute as the attribute doesn't have a prefix
                if namespace is None or ns != namespace and prefix != '*':
                    continue

                # The attribute doesn't match.
                if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):
                    continue

                value = v
                break
        else:
            for k, v in self.iter_attributes(el):
                if util.lower(attr) != util.lower(k):
                    continue
                value = v
                break
        return value
1269744
private String readNamespaceAttr(Document doc) {

    	// lazy loading is mostly pointless but it keeps things together
    	if (namespaceExpr == null) {
    		namespaceExpr = initNamespaceAttrExpression();
    	}

		String s;
		try {
			s = namespaceExpr.evaluate(doc);
		} catch (XPathExpressionException e) {
			throw new PluginException("Error evaluating namespace XPath expression: " + e, e);
		}
		// xpath returns an empty string if not found, null is cleaner for callers
		return (s == null || s.length() == 0) ? null : s;
    }
254992
static String getAttributeValue(Element element, String name) {
        Attr attribute = element.getAttributeNode(name);
        if (attribute == null) {
            return null;
        } else {
            return attribute.getValue();
        }
    }
11041
function getAttrMap(attrs)
{
	var i;
	var map = {};
	var numAttrs = attrs.length;
	
	for (i=0; i<numAttrs; i++)
	{
		map[ attrs[i].name ] = attrs[i].value;
	}
	
	return map;
}
695103
private static void getNamespaceBindings(Element element, Map<String, String> namespaceMap) {
    if (element == null) {
      return;
    }
    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
      Node node = attrs.item(i);
      String name = node.getNodeName();
      if ((name != null && (XMLConstants.XMLNS_ATTRIBUTE.equals(name) || name.startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")))) {
        namespaceMap.put(name, node.getNodeValue());
      }
    }
    Node parent = element.getParentNode();
    if (parent instanceof Element) {
      getNamespaceBindings((Element) parent, namespaceMap);
    }
  }