Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the XPath equivalent of the Coalesce operator?

Tags:

xpath

I have the following paths:

  • /my:company/ns1:Audit/ns1:Visit/ns1:customField10
  • /my:company/ns1:Audit/ns1:Visit/ns1:accountNumber

I want to select ns1:customField10 if it is not empty, otherwise I want to return ns1:accountNumber.

I tried the following:

xml.SelectSingleNode(
    "(/my:cobius/ns1:Audit/ns1:Visit/ns1:customField10 | 
    /my:cobius/ns1:Audit/ns1:Visit/ns1:accountNumber)", ns)

But it is always returning accountNumber. I tried flipping the order of customField10 and accountNumber, but no joy. It still returns accountNumber.

How can I do the equivalent of the coalesce operator in XPath?

Update:

Here's the final code:

xml.SelectSingleNode(
    "(/my:company/ns1:Audit/ns1:Visit/ns1:customField10[normalize-space()] | 
    /my:company/ns1:Audit/ns1:Visit/ns1:accountNumber[not(normalize-space(../ns1:customField10))])", ns)
like image 284
Rich Bennema Avatar asked Jan 25 '12 19:01

Rich Bennema


1 Answers

Your code would work if the node was missing (kind of equivalent to a NULL in SQL). But empty is not missing (like an empty string in SQL).

You can of course add a predicate:

/my:cobius/ns1:Audit/ns1:Visit/ns1:customField10[string-length(.)] | /my:cobius/ns1:Audit/ns1:Visit/ns1:accountNumber
like image 193
Lucero Avatar answered Nov 16 '22 08:11

Lucero