I want to extract some content from a web page's XML equivalent, using XQuery.
Here, I want to use if-then-else -- if a specific condition is met, then one value is returned by the xquery expression, otherwise a different value is returned.
This is the expression I have with me--
I am working to extract some content from a web page.
Given below is the Xquery code I am using-- I am using a XQuery library to parse through XML which is obtained by transforming a HTML web page into XML...after that I am extracting some specific content from that XML page...
declare variable $doc as node() external;
let $select_block := $doc//div[@class="randomclass" and contains(.,'MatchingText')]
for $select_link in $select_block/a
for $select_link_url in $select_link/@href
where contains($assignee_link_url,'inassignee')
return data($select_link)
Now how do I use if-then-else within this expression?
I tried to add an if-then immediately after 'return' keyword but I am getting error... Basically, if some content is found for $select_block above, then data($select_link) should be returned, otherwise the static text 'Missing Value' should be returned.
What is the correct way of using if-then-else with the above xquery expression?
If I understand what you are trying to achieve correctly, then the following should work:
declare variable $doc as node() external;
let $select_block := $doc//div[@class="randomclass" and contains(.,'MatchingText')]
return
if ($select_block) then
for $select_link in $select_block/a
for $select_link_url in $select_link/@href
where contains($select_link_url,'inassignee')
return data($select_link)
else 'Missing Value'
You could simplify things a little bit and eliminate the nested for loops with predicate filters selecting the anchor elements:
declare variable $doc as node() external;
let $select_block := $doc//div[@class="randomclass" and contains(.,'MatchingText')]
return
if ($select_block) then
for $select_link in $select_block/a[@href[contains(., 'inassignee')]]
return data($select_link)
else 'Missing Value'