Java 无法从xml字符串构造文档对象

Java 无法从xml字符串构造文档对象,java,xml,xpath,xml-parsing,Java,Xml,Xpath,Xml Parsing,我的应用程序中有如下xml字符串 <?xml version="1.0" encoding="UTF-8"?><loc:getLocation xmlns:loc="http://www.csapi.org/schema/parlayx/terminal_location/v2_3/local"> <loc:address>tel:+919420161525</loc:address> <loc:requestedAccu

我的应用程序中有如下xml字符串

<?xml version="1.0" encoding="UTF-8"?><loc:getLocation xmlns:loc="http://www.csapi.org/schema/parlayx/terminal_location/v2_3/local">
     <loc:address>tel:+919420161525</loc:address>
     <loc:requestedAccuracy>500</loc:requestedAccuracy>
     <loc:acceptableAccuracy>500</loc:acceptableAccuracy>
  </loc:getLocation>
但我得到的文档对象为null。我不知道;我没有任何例外。我尝试在线验证我的XML,但没有发现任何错误


知道我做错了什么吗

正如Arthur Elrich在评论中指出的,您应该让工厂名称空间感知,并为XPath实例提供名称空间上下文

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();  
Document document = builder.parse( new InputSource(new StringReader(...)));

XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new MyNamespaceContext());
String s = xpath.evaluate("//location:address/text()", document);
System.out.println(s2);
以及简化的
名称空间上下文
实现:

static class MyNamespaceContext implements NamespaceContext {

    @Override
    public String getNamespaceURI(String prefix) {
        switch (prefix) {
        case "location":
            return "http://www.csapi.org/schema/parlayx/terminal_location/v2_3/local";
        }
        return null;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        return null;
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        return null;
    }

}
请注意,XPath表达式中使用的前缀与文档中使用的前缀不同。它们当然可以是相同的,但本例表明,重要的是名称空间URI,而不是前缀

另一种方法是,使用
local name
函数,您可以不知道名称空间:

xpath.evaluate("//*[local-name() = 'address']/text()", document);

然而,这个替代方案的健壮性要差得多,因为它将检索所有名为
address
的元素,而不管它们的实际名称空间是什么。

头是什么?header.concat(str)的结果是什么?如果XML是有效的,为什么要在开始时添加一些内容呢?还要注意,此XML是一个名称空间的XML,这意味着您可能也需要实现名称空间上下文。JP Moresmau,很抱歉混淆,“header”不存在。它的新StringReader(str),其中str是我提到的xml字符串。Arthur,我不明白你的意思,你能详细说明一下吗?当你说“把文档对象设为空”时,你是怎么确定的?如果没有异常,
document
变量的值将不是Java
null
,而是非null
document
DOM节点的toString表示(即从
System.out.println(document)
)是类似于
的字符串[#document:null]”
。这意味着文件还没有形成,对吗?如果我使用类似xpath.evaluate的xpath访问地址(“loc:address/text()”,document);我的地址是空的,我通过其他方式得到了它。不过,您的解决方案也很有效。干杯
xpath.evaluate("//*[local-name() = 'address']/text()", document);