XML namespace defaulting/inheritance

java, xml

Solution

To the best of my knowledge, all the standard XML APIs in Java support namespaces. Many of the APIs were written before namespaces were created (or became popular - I can no longer remember). You often need to enable support:

public class NS {
  private static void print(Node node) {
    Queue<Node> nodes = new LinkedList<Node>();
    nodes.add(node);
    while (!nodes.isEmpty()) {
      node = nodes.poll();
      NodeList list = node.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        nodes.add(list.item(i));
      }
      System.out.format("%s %s %s%n", node.getPrefix(), node.getLocalName(),
          node.getNamespaceURI());
    }
  }

  public static void main(String[] args) throws Exception {
    String xml = "<a xmlns=\"http://domain/a\">"
        + "<pre:b xmlns:pre=\"http://domain/b\">" + "<c/>" + "<d xmlns=\"\">"
        + "<e/>" + "</d>" + "</pre:b>" + "</a>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(
        new InputSource(new StringReader(xml)));
    print(doc.getDocumentElement());
  }
}

This code will print:

null a http://domain/a
pre b http://domain/b
null c http://domain/a
null d null
null e null

Problem

In the below XML snippet what are the namespaces of a, c, d and e? Reference to documentation or specifications would be appreciated. ``` <a xmlns="http://domain/a"> <pre:b xmlns:pre="http://domain/b"> <c/> <d xmlns=""> <e/> </d> </pre:b> </a> ``` Also, what Java frameworks respect the official namespace defaulting? I have tride org.w2c.* DOM packages, however it does not seem to resolve the namespace URI correctly? For example, something with similar functionality to. ``` String namespace = DocumentParser.parse(). getElement("a"). getElement("b"). getElement("c"). getNamespaceURI(); ```

Original source