如何在java中使用XPath解析此xml?

如何在java中使用XPath解析此xml?,java,xml,xpath,xml-namespaces,Java,Xml,Xpath,Xml Namespaces,2.0 我在使用XPath 1.0解析时遇到了一些问题 我就是这么做的: XPath=XPath.newInstance(“/double”); 元素returnElement=(元素)xpath.selectSingleNode(doc); 返回元素为null,但应为2.0 注意:它应该使用XPath1.0双元素在http://www.somewebsite.com/名称空间。将名称空间映射到前缀(例如foo),并使用限定表达式(例如/foo:double)进行解析 使用标准API: St


2.0

我在使用XPath 1.0解析时遇到了一些问题

我就是这么做的:


XPath=XPath.newInstance(“/double”);
元素returnElement=(元素)xpath.selectSingleNode(doc);

返回元素为null,但应为2.0


注意:它应该使用XPath1.0

元素在
http://www.somewebsite.com/
名称空间。将名称空间映射到前缀(例如
foo
),并使用限定表达式(例如
/foo:double
)进行解析

使用标准API:

String xml = "<double xmlns='http://www.somewebsite.com/'>2.0</double>";
Reader reader = new StringReader(xml);
XPath xpath = XPathFactory.newInstance()
                          .newXPath();
NamespaceContext context = new NamespaceContextMap("foo", "http://www.somewebsite.com/");
xpath.setNamespaceContext(context);
String value = xpath.evaluate("/foo:double", new InputSource(reader));
System.out.println(value);
stringxml=“2.0”;
Reader=新的StringReader(xml);
XPath=XPathFactory.newInstance()
.newXPath();
NamespaceContext上下文=新的NamespaceContextMap(“foo”http://www.somewebsite.com/");
setNamespaceContext(context);
String value=xpath.evaluate(“/foo:double”,新的InputSource(reader));
系统输出打印项次(值);

您可以在上找到的示例实现。

correct Xpath“/double/text()”@user1516873:尝试过。没用。在此处找到答案:。它应该是“/*[local-name()='double']”