Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么getLocalName()返回null?_Java_Xml - Fatal编程技术网

Java 为什么getLocalName()返回null?

Java 为什么getLocalName()返回null?,java,xml,Java,Xml,我正在加载一些XML字符串,如下所示: Document doc = getDocumentBuilder().parse(new InputSource(new StringReader(xml))); 稍后,我将从该文档中提取一个节点: XPath xpath = getXPathFactory().newXPath(); XPathExpression expr = xpath.compile(expressionXPATH); NodeList nodeList = (NodeList

我正在加载一些XML字符串,如下所示:

Document doc = getDocumentBuilder().parse(new InputSource(new StringReader(xml)));
稍后,我将从该
文档中提取一个节点:

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
通过调试器,我看到我的节点具有以下类型:

声明此类型节点的
getLocalName()
返回
null

  • 为什么节点的类型为文档\位置\断开连接,而不是元素\节点
  • 如何“转换”节点的类型
如文件所述:

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

因此,请确保将命名空间感知的
DocumentBuilderFactory
setNamespaceAware(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);

因此(至少)您的本地名称问题是由使用DOM级别1而不是名称空间感知文档(构建器工厂)引起的。

如何显示一个最小但完整的示例,让我们重现该问题?向我们展示
xml
expressionXPATH
。您是否使用了名称空间感知的
DocumentBuilderFactory
?至少,展示您正在使用的XPath表达式。如何知道使用的是哪种DOM级别?如果您想查询现有的实现,您需要查看以测试各种支持的功能。但我不完全确定这有多精确,我只知道对于有意义的XPath来说,使用名称空间感知DOM是必不可少的。
true
false