Why does getLocalName () return null?

I load some XML lines as follows:

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

Later I will extract 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 a debugger, I saw that my node has the following type: DOCUMENT_POSITION_DISCONNECTED .

Javadoc claims to getLocalName()return a nullnode for this type.

  • Why is node type DOCUMENT_POSITION_DISCONNECTED and not ELEMENT_NODE?
  • How to "convert" node type?
+4
source share
1 answer

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

, DOM Level 1, [...] null

, DocumentBuilderFactory setNamespaceAware(true) , DOM DOM- DOM 2/3 getLocalName().

    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);

true
false

( ) , DOM 1, , (builder factory).

+3

Source: https://habr.com/ru/post/1671284/


All Articles