1

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)
)
user1424739
  • 11,937
  • 17
  • 63
  • 152

3 Answers3

2

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
  ),
  "	"
)
Reino
  • 3,203
  • 1
  • 13
  • 21
1

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
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • I don’t want to rewrite the whole join statement. Is there a way to assign the middle column value to a variable depending on whether $x/span is empty or not? – user1424739 Jul 26 '20 at 04:14
  • @user1424739, you don't need to rewrite the entire `join` statement. Just replace the `$x/span` with the expression I showed. – Yitzhak Khabinsky Jul 26 '20 at 04:21
1

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.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • For my case, $x/span can return either 0 or 1 element. So this works for my case. And this solution is more succinct than the solution by @YitzhakKhabinsky. So I'd consider this solution is better. – user1424739 Jul 26 '20 at 11:06