jcabi/jcabi-xml

XPath with a namespace does not work

gicoprasico opened this issue · 3 comments

Hi i tried this simple example, and i am getting an error:

XML xmlRequest = new XMLDocument("<a xmlns='urn:foo'><b>yes!</b></a>"); xmlRequest.registerNs("foo", "urn:foo"); String result = xmlRequest.xpath("//foo:b/text()").get(0);

The error I receive is:

java.lang.IllegalArgumentException: invalid XPath query '//foo:b/text()' at org.apache.xpath.jaxp.XPathFactoryImpl at org.apache.xpath.compiler.XPathParser.errorForDOM3(XPathParser.java:655) at org.apache.xpath.compiler.Lexer.mapNSTokens(Lexer.java:647) at org.apache.xpath.compiler.Lexer.tokenize(Lexer.java:274) at org.apache.xpath.compiler.Lexer.tokenize(Lexer.java:98) at org.apache.xpath.compiler.XPathParser.initXPath(XPathParser.java:112) at org.apache.xpath.XPath.<init>(XPath.java:178) at org.apache.xpath.XPath.<init>(XPath.java:266) at org.apache.xpath.jaxp.XPathImpl.eval(XPathImpl.java:195) at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:281) at com.jcabi.xml.XMLDocument.fetch(XMLDocument.java:429) at com.jcabi.xml.XMLDocument.xpath(XMLDocument.java:324)

I am using the 1.0-SNAPSHOT version of jcabi-xml.

0crat commented

@yegor256 please, pay attention to this issue

Disclaimer: I'm not a jcabi-xml owner, my answer just came from my experience of its usage.

XMLDocument is immutable. So, to apply a namespace, you must chain the calls, like that:

XML xmlRequest = new XMLDocument("<a xmlns='urn:foo'><b>yes!</b></a>").registerNs("foo", "urn:foo");
String result = xmlRequest.xpath("//foo:b/text()").get(0);

Hi Skarpal. Thanks for your answer! It works!