I'm trying to learn xQuery coming from a php background, I have this expression working as expected
<![CDATA[
declare variable $doc as node() external;
declare variable $id external;
let $cont := data($doc//div[@class="cont"])
let $title := data($doc//p[@class="vtitle"])
let $text := data($doc//div[@class="venue-cont-left"])
return
<venue id="{$id}">
<title>{$title}</title>
<text>{$text}</text>
</venue>
]]>
However now I simply want to make a check weather $title is empty or not
<![CDATA[
declare variable $doc as node() external;
declare variable $id external;
if(empty(data($doc//p[@class="vtitle"]))) then
(
let $id :=$id
return
<venue id="{$id}" />
) else (
let $cont := data($doc//div[@class="cont"])
let $title := data($doc//p[@class="vtitle"])
let $text := data($doc//div[@class="venue-cont-left"])
return
<venue id="{$id}">
<title>{$title}</title>
<text>{$text}</text>
</venue>
)
]]>
This does not work because i get this resulting output
<venue id="4">
<title/>
<text>
PHONE:
ADDRESS:....
As you see venue 4 has no title so it should have been returned as <venue id="4" />
Thanks for any help!
Use:
declare variable $doc as node() external;
declare variable $id external;
declare variable $title := data($doc//p[@class="vtitle"]);
<venue id="{$id}">{
if ($title)
then <title>{$title}</title>
else (),
<text>{data($doc//div[@class="venue-cont-left"])}</text>
}</venue>
Note: Empty sequence efective boolean value is false.
There is only one scenario I can think of where your query fails: If your XML contains a p node like this with no content:
<p class="vtitle" />
With this, the following code snippet returns a zero-length string "" (not an empty sequence):
data($doc//p[@class="vtitle"])
The problem here is that the function empty() checks for an empty sequence. Therefore, empty("") returns false.
If you would leave away the empty() and switch the then and else expressions your code should work, because then the Effective Boolean Value (EBV) is processed. And, the EBV of an empty string as well as of an empty sequence is false.
Hope that makes sense?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With