wood burning stoves 2.0*
The moose likes XML and Related Technologies and the fly likes XPath: Check if a node actually exists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "XPath: Check if a node actually exists" Watch "XPath: Check if a node actually exists" New topic

XPath: Check if a node actually exists

Chris Corbyn
Ranch Hand

Joined: Jan 14, 2007
Posts: 114
Using javax.xml.xpath.XPath...

If I have an XML file like this:

And I run an expression to get the value of a Node which doesn't even exist:

I get an empty string back. Now from that I can't deduce whether there's a tag there but it's got no content in it, or if it's just not there at all. Is there any way of checking if the node exists using an XPath expression or do I have to actually dive into the DOM to do this?

EDIT | Apologies, I've been sitting watching posts in this forum for the past few days and completely forgot to select a more appropriate forum for this question.
[ August 06, 2007: Message edited by: Chris Corbyn ]
Paul Clapham

Joined: Oct 14, 2005
Posts: 18541

XPath is certainly one of the "Related Technologies" in the name of this forum, so this is the best place for your question.

If you are getting an empty string, then you must be issuing your XPath query in such a way that you get a string result. If you change it so that you request a nodeset result, you should get a nodeset with zero nodes in it when there are no nodes matching the expression.
Chris Corbyn
Ranch Hand

Joined: Jan 14, 2007
Posts: 114
Perfect, and so obvious. Doh! I tried BOOLEAN but it always returned true when the node didn't exist. NodeSet should work a treat logically.
I agree. Here's the link: http://aspose.com/file-tools
subject: XPath: Check if a node actually exists
Similar Threads
XPath expression constrained by a predicate doesn't work (//element[@attribute="value"])
Regex for adding CDATA to XML nodes
have node object, need to view it's xml?
xslt conditionally displaying node elements
XML Parsing