Xalan-j XPathAPI and namespaces

D

Dino Morelli

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

Dino Morelli

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");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top