为什么getLocalName()返回null?

史蒂芬:

我正在加载这样的XML字符串:

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

稍后,我从中提取一个节点Document

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

Node node = nodeList.item(0);

现在,我想获取此节点的本地名称,但得到null

node.getLocalName(); // return null

使用调试器,我看到我的节点具有以下类型:DOCUMENT_POSITION_DISCONNECTED

Javadoc指出针对此类型的节点getLocalName()返回的null值。

  • 为什么节点是DOCUMENT_POSITION_DISCONNECTED类型而不是ELEMENT_NODE类型?
  • 如何“转换”节点的类型?
马丁·洪恩(Martin Honnen):

正如文档https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getLocalName()所述:

对于使用DOM Level 1方法创建的节点,[...]始终为空

因此请务必使用一个名称空间感知的DocumentBuilderFactorysetNamespaceAware(true),这样的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 Level 1(而不是名称空间感知的文档)(生成器工厂)引起的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章