Re: XPath with default namespace - No result
Nathan Nadeau <[email protected]> Wed, 08 Feb 2012 21:48:39 -0500
| Newsgroups | gmane.text.xml.xalan.java.user |
|---|---|
| Organization | Gleim Publications |
| Message-ID | <[email protected]> |
Olivier,
As Gareth mentioned in your JIRA post, what's happening is that the
<report> and <account_number> elements are still bound to the
"http://www.mydomain.com/report" namespace, even though they are not
using a namespace prefix. Your XML is using a declared default namespace
of "http://www.mydomain.com/report".
Therefore your XPath query will not return anything because it is asking
for <report> and <account_number> elements that are in no namespace
(because you haven't defined a namespace context), but your input XML
only contains elements in the "http://www.mydomain.com/report" namespace.
If you can't control your input XML, then you need to set your namespace
context so that the XPath query knows you are looking for <report> and
<account_number> in the "http://www.mydomain.com/report" namespace.
These pages should provide good instructions and hints:
http://xml.apache.org/xalan-j/xpath_apis.html#namespacecontext
http://www.edankert.com/defaultnamespaces.html
Good luck,
Nathan
Olivier Roger wrote:
> Hi,
>
> I am having difficulties to use XPath query on a XML dataset having its root
> element with an *xmlns attribute with no prefix*.
>
> In that specific case, the XPath query does not return the value. Since I
> have no prefix for the namespace I simply can get the value.
> It this a known issue or am I simply doing something wrong ?
>
> Here is my XML :
>
> {noformat:title=default-ns.xml}
> <?xml version="1.0" encoding="UTF-8"?>
>
> <report xmlns="http://www.mydomain.com/report">
> <account_number>123</account_number>
> </report>
> {noformat}
>
> Here is my test method:
>
> {code}
> @Test
> public void xPathDefaultNS() throws XPathExpressionException {
> javax.xml.xpath.XPathFactory factory =
> javax.xml.xpath.XPathFactory.newInstance();
> javax.xml.xpath.XPath xpath = factory.newXPath();
> javax.xml.xpath.XPathExpression expression =
> xpath.compile("/report/account_number");
> String result = expression.evaluate(new
> org.xml.sax.InputSource(this.getClass().getResourceAsStream("default-ns.xml")));
> Assert.assertTrue("123".equals(result));
> }
> {code}
>
> From what Gareth responded on the Jira issue
> (https://issues.apache.org/jira/browse/XALANJ-2549) there seems to be a
> missing step (resolving the namespace). How I that done exactly ?
>
>
>
--
Nathan Nadeau
[email protected]
Software Development
Gleim Publications, Inc.
http://www.gleim.com