Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Xalan-j XPathAPI and namespaces

1 view
Skip to first unread message

Dino Morelli

unread,
Nov 3, 2003, 2:45:08 PM11/3/03
to
Looking for someone familiar with Xalan-j..

I'm having problems isolating a node in a Document with Xalan-j's
XPathAPI class when that element is in a namespace.

using:
Xalan-j v2.5.1
JDK v1.4.2-b28

Given an XML document that looks like this:

<a xmlns:foo="foo-ns">
<b>value 1</b>
<foo:b>value 2</foo:b>
</a>

These calls return null:

// Document doc contains the parsed above document
Node n = XPathAPI.selectSingleNode(doc, "/a/foo:b");
Node n = XPathAPI.selectSingleNode(doc, "/a/foo:b",
doc.getDocumentElement());

However, this xpath works, retrieving the second b with no namespace
explicitly requested:

"/a/b[2]"


Does anyone know how to make the first type of xpath "/a/food:b" work?


--
Dino Morelli dino.m...@snet.net .~.
http://www.debian.org Debian GNU/Linux /V\
/( )\
^^-^^

Dino Morelli

unread,
Nov 3, 2003, 10:24:26 PM11/3/03
to
On Mon, 3 Nov 2003, Dino Morelli wrote:

>I'm having problems isolating a node in a Document with Xalan-j's
>XPathAPI class when that element is in a namespace.
>

>Given an XML document that looks like this:
>
><a xmlns:foo="foo-ns">
> <b>value 1</b>
> <foo:b>value 2</foo:b>
></a>
>
>These calls return null:
>
>// Document doc contains the parsed above document
>Node n = XPathAPI.selectSingleNode(doc, "/a/foo:b");
>Node n = XPathAPI.selectSingleNode(doc, "/a/foo:b",
> doc.getDocumentElement());
>

I figured this out for myself.

When constructing the DocumentBuilder to parse the XML, you must set up
the DocumentBuilderFactory like this:

DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ important part

Then get your DocumentBuilder:

DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(/* yada yada RTFM */);

In order for subsequent XPath processing to be namespace aware.
Then this is all that's necessary to use it:

Node n = XPathAPI.selectSingleNode(doc, "/a/foo:b");

0 new messages