[英]xQuery simple if not empty conditional
I'm trying to learn xQuery coming from a php background, I have this expression working as expected 我正在尝试学习来自php背景的xQuery,我让这个表达式按预期工作
<![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 但是现在我只是想检查天气$ title是否为空
<![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" />
如你所见,场地4没有标题所以应该以<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. 注意 :空序列有效布尔值为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: 只有一种情况我可以想到你的查询失败的地方:如果你的XML包含像这样没有内容的p
节点:
<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. 这里的问题是函数empty()
检查空序列。 Therefore, empty("")
returns false
. 因此, empty("")
返回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. 如果你要离开empty()
并切换then和else表达式你的代码应该工作,因为那时处理有效布尔值(EBV)。 And, the EBV of an empty string as well as of an empty sequence is false
. 并且,空字符串以及空序列的EBV是false
。
Hope that makes sense? 希望有道理吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.