0

<?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.

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.

NOTE: It should be using XPath 1.0

pnuts
  • 58,317
  • 11
  • 87
  • 139
Chanthu
  • 1,794
  • 1
  • 15
  • 22
  • correct Xpath "/double/text()" http://stackoverflow.com/questions/5033955/xpath-select-text-node – user1516873 Mar 22 '13 at 08:49
  • @user1516873: Tried that. didn't work. Found the answer here: [link](http://stackoverflow.com/a/15240082/841804). it should be "//*[local-name()='double']" – Chanthu Mar 22 '13 at 08:58

1 Answers1

0

The double element is in the http://www.somewebsite.com/ namespace. Map the namespace to a prefix (e.g. foo) and resolve with a qualified expression (e.g. /foo:double).

Using the standard 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.

McDowell
  • 107,573
  • 31
  • 204
  • 267