views:

48

answers:

1

I have an XML Schema element like this:

<xs:element type="xs:string" name="IsActive" minOccurs="0"> </xs:element>

I'm using dom4j XPath to evaluate the element.

It seems impossible to determine whether element is present in the XML document or if its value is simply "".

I want <IsActive> to be either, 1) "" 2) "anyvalue1" 3) "anyvalue"

Also I would like to know if <IsActive> is present.

XPath valuePath;
Node obj = (Node)valuePath.selectSingleNode(requestElement);

obj.getText() always returns "", even if <IsActive> is not present.

valuePath.valueOf(requestElement); // does the same

So my question is: How to distinguish null and empty string?

+1  A: 

How about:

List nodeList = valuePath.selectNodes(requestElement);
if (nodeList.isEmpty()) ...

Update: @Alejandro pointed out that it would be helpful to add explanations.

Apparently selectSingleNode() does not return null or offer any other way to distinguish between an XPath expression and context that result in an empty nodeset, vs. those that yield one or multiple nodes. So that will not meet the present need.

However, selectNodes() returns a List of nodes matching the XPath expression in the given context. So presumably we can use the List.isEmpty() method (or the size() method) to discover whether the XPath matched zero nodes, or non-zero.

If a node is matched, to get the (first) matched node we can use nodeList.get(0):

List nodeList = valuePath.selectNodes(requestElement);
if (!nodeList.isEmpty())
    doSomethingWith(nodeList.get(0));

I have not tested this, but it should get you within reach of your goal.

LarsH
This is right but missing XPath and Dom4j explanations: OP needs to test for empty node set; it looks like there is no `null` result for `selectNodes` method nor empty node test for `Node` class in Dom4j; there is an `isEmpty` method for `List` class. Also, the class `Node` casting is not needed (and maybe wrong, I didn't test)
Alejandro
@Alejandro, oops, you're right about the cast... it's wrong. Fixed it - thanks.
LarsH