简体   繁体   English

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

[英]How to parse this xml using XPath in java?

<?xml version="1.0" encoding="utf-8"?> <double xmlns="http://www.somewebsite.com/">2.0</double>

I'm having a bit of trouble parsing this using XPath 1.0. 我在使用XPath 1.0解析时遇到了一些麻烦。

this is what i do: 这就是我的工作:

XPath xpath = XPath.newInstance("/double"); Element returnElement = (Element) xpath.selectSingleNode(doc);

the return element is null but it should be 2.0. 返回元素为null,但应为2.0。

NOTE: It should be using XPath 1.0 注意:它应该使用XPath 1.0

The double element is in the http://www.somewebsite.com/ namespace. double元素位于http://www.somewebsite.com/命名空间中。 Map the namespace to a prefix (eg foo ) and resolve with a qualified expression (eg /foo:double ). 将名称空间映射到前缀(例如foo ),并使用限定的表达式(例如/foo:double )进行解析。

Using the standard API: 使用标准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);

You can find a sample implementation of NamespaceContext on my blog . 您可以在我的博客上找到NamespaceContext的示例实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM