user1578871
user1578871

Reputation: 53

xquery beginner- how to give a specific default value to a variable when there is no content in xml for that variable

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)

From above, you can see that variable $select_block tries to extract content of that div of web page which has class="randomclass", and which contains the text "MatchingText".

Now, if the web page in question does not contain such a block, then how do I return a default value for $select_link? Basically, I want to tackle the scenario where no value is returned for a selection within an XQuery expression so that I can mark a flag that tells the user that this value was not found.

Upvotes: 0

Views: 2146

Answers (1)

Christian Grün
Christian Grün

Reputation: 6229

An if/then/else construct will probably do what you want. An example:

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($assignee_link_url,'inassignee')  
  return data($select_link)
) else (
  'default value'
)

Upvotes: 0

Related Questions