开发者

Dom4j XPath distinguish null or empty string

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.se开发者_StackOverflow中文版lectSingleNode(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜