Skip to main content

xPaths problem

1 reply [Last post]
Joined: 2008-04-23

Hi all,

I'm using xPath in order to retrieve data from my parsed DOM tree.
One the the tags in my xml contains colon: .
It seems that when I try to get the data after the evaluate function - this doesn't succeed.
Meaning, this won't succeed using xPath (returns null) : XPathExpression expr = xpath.compile("/service/screen/media:image");
It works fine with tags that do not contain colon.
Is there a way to solve this?

Thanks in advance,

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-05-06


This seems to be an issue with namespaces. Firstly, did you load the DOM with namespaces enabled? - (DocumentBuilderFactory.setNamespaceAware(true) - easy to make this mistake as the default is false).

Secondly, if you are dealing with namespaces and prefixes in your XML, you'll need to set up a NamespaceContext on your XPath object (see setNamespaceContext()). Unfortunately a default implementation does not exist in the JDK (just an interface) so you'll need to implement one yourself.

Lastly, I've had problems when using the null prefix in XPath expressions and namespace contexts. So you may want to use a prefix for all namespaces in your XPath expression. The prefixes do not have to match what's in your XML, just the namespace URIs so you can map them how you like for your XPath expression.

Here's some really quick 'n' dirty code to clarify:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
XPathFactory xpf = XPathFactory.newInstance();
String xml = "test";
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
XPath xPath = xpf.newXPath();
xPath.setNamespaceContext(new NamespaceContext()
public String getNamespaceURI(final String prefix)
if ("media".equals(prefix))
else if ("a".equals(prefix))
public String getPrefix(final String namespaceURI)
throw new UnsupportedOperationException("not written");
public Iterator getPrefixes(final String namespaceURI)
throw new UnsupportedOperationException("not written");
XPathExpression expr = xPath.compile("/a:service/a:screen/media:image");
String result = expr.evaluate(doc);
System.out.println("Result: " + result); //Should be 'test'

Good luck!