Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getLocalName() return null?

Tags:

java

xml

I'm loading some XML string like this:

Document doc = getDocumentBuilder().parse(new InputSource(new StringReader(xml)));

Later, I extract a node from this Document:

XPath xpath = getXPathFactory().newXPath();
XPathExpression expr = xpath.compile(expressionXPATH);
NodeList nodeList = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);

Node node = nodeList.item(0);

Now I want to get the local name of this node but I get null.

node.getLocalName(); // return null

With the debugger, I saw that my node has the following type: DOCUMENT_POSITION_DISCONNECTED.

The Javadoc states that getLocalName() returns null for this type of node.

  • Why node is of type DOCUMENT_POSITION_DISCONNECTED and not ELEMENT_NODE?
  • How to "convert" the type of the node?
like image 432
Stephan Avatar asked Mar 02 '17 18:03

Stephan


1 Answers

As the documentation https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getLocalName() states:

for nodes created with a DOM Level 1 method, [...] this is always null

so make sure you use a namespace aware DocumentBuilderFactory with setNamespaceAware(true), that way the DOM is supporting the namespace aware DOM Level 2/3 and will have a non-null value for getLocalName().

A simple test program

    String xml = "<root/>";

    DocumentBuilderFactory db = DocumentBuilderFactory.newInstance();

    Document dom1 = db.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

    System.out.println(dom1.getDocumentElement().getLocalName() == null);

    db.setNamespaceAware(true);

    Document dom2 = db.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

    System.out.println(dom2.getDocumentElement().getLocalName() == null);

outputs

true
false

so (at least) the local name problem you have is caused by using a DOM Level 1, not namespace aware document (builder factory).

like image 143
Martin Honnen Avatar answered Sep 20 '22 08:09

Martin Honnen