How to deal with empty node in xquery?

553 views Asked by At

I want to print a TSV output like this. But when $x/span does not find anything, there will be only two columns printed. How to insert an empty field in the 2nd column when $x/span finds nothing? Thanks.

for $x in //td/b/a[@title]/parent::b/parent::td
return join(
    (
        $x/b/a/@title
        , $x/span
        , $x/p
    )
    , x:cps(9)
)
3

There are 3 answers

0
Reino On BEST ANSWER

XPath:

//td[b/a[@title]]/join(
  (
    b/a/@title,
    (span,"")[1],
    p
  ),
  x:cps(9)
)

XQuery:

for $x in //td[b/a[@title]] return
$x/join(
  (
    b/a/@title,
    (span,"")[1],
    p
  ),
  "	"
)
2
Yitzhak Khabinsky On

You can use if/else statement to control what to do in case of the missing span tag.

if (empty($x/span)) then  
    (: do what you need here :)
else  
    $x/span
1
Michael Kay On

A common idiom for this is

($x/span, "default")[1]

But this might not be right for you if $x/span can select multiple items.