使用 xPath,我从 html 字段中获取数据,此数据可以采用以下格式(包括括号):
DATA |||| symbols i'm using to explain my code
(bornPlace, bornDate-DeathDate) |||| (str, A-B) = note that str may also contain '-'
(bornPlace, bornDate) |||| (str, A)
(bornPlace) |||| (str)
(bornDate-DeathDate) |||| (A-B)
(bornDate) |||| (A)
Or completely empty
我正在尝试使用多个 if-else 语句将每个元素检索到单独的变量中,但它似乎不喜欢多行命令(我认为是这样)。
我已经编写了一个无法正常工作的代码:-/(它说期待返回,发现其他如果......)
let $temp1 := data(normalize-space(substring-before(substring-after(//div/div[2]/h2/text(), '('), ')')))
if (contains($temp1,',')) (: (str, A-B) or (str, A) :)
then
let $bornPlace := substring-before($temp1, ',')
let $temp2 := substring-after($temp1, ',')
if (contains($temp2,'-'))
then
let $bornDate := substring-before($temp2, '-')
let $deathDate := substring-after($temp2, '-')
else
let $bornDate := $temp2
let $deathDate := data('')
else if (contains($temp1,'-'))
then (: (s-t-r) or (A-B) :)
let $temp2 := normalize-space(substring-before($temp1, '-'))
if (number($temp2)=$temp2) (: it's a number :)
then
let $bornDate := temp2
let $deathDate := normalize-space(substring-after($temp2, '-'))
let $bornPlace := data('')
else
let $bornPlace := $temp1
let $bornDate := data('')
let $deathDate := data('')
else (: (str) or (A) :)
if (number($temp1)=$temp1) (: it's a number :)
then
let $bornDate := temp1
let $deathDate := data('')
let $bornPlace := data('')
else
let $bornPlace := $temp1
let $bornDate := data('')
let $deathDate := data('')
此外,如果有更漂亮的方法来做到这一点,我会接受 :D
在此先感谢您的帮助:)
最佳答案
let 子句不是表达式。你需要改变这种逻辑
if (contains($temp2,'-'))
then
let $bornDate := substring-before($temp2, '-')
let $deathDate := substring-after($temp2, '-')
else
let $bornDate := $temp2
let $deathDate := data('')
由此
let $hyphenated := contains($temp2, '-')
let $bornDate := if ($hyphenated) then substring-before($temp2, '-') else $temp2
let $deathDate := if ($hyphenated) then substring-after($temp2, '-') else ''
return ...
虽然在这种特殊情况下我会倾向于写:
let $tokens := tokenize($temp2, '-')
let $bornDate := $tokens[1]
let $deathDate := string($tokens[2])
return ...
关于xml - xquery 多 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11665962/