是否可以在XQuery的where子句中使用OR?

时间:2016-04-07 20:33:44

标签: xml database xpath xquery basex

我需要返回“John Doe”是作者的书籍和期刊的标题,但我的xml文件设置为:

<library>
<book>...</book>
<article>...</article>
</library>

共有6本书籍和期刊。

我知道如果这是SQL我可以做类似的事情:

SELECT title
FROM library
WHERE bookauthor = "John Doe" OR articleauthor = "John Doe"

该数据库不会被规范化,但我想表明我认为我知道我需要做什么,只是不确定如何使用XQuery

我尝试了以下内容,它将所有6个标题归还给我:

for $x in doc("xmldata.xml")/library
let $a := $x/article
let $b := $x/book
return ($a/title, $b/title)

但我不知道如何处理where子句。同样地,我尝试了以下内容并陷入同一点:

for $x in doc("xmldata.xml")/library
return ($x/article/title, $x/book/title)

当我尝试添加一个where子句时,它仍会返回所有6个条目,即使它只返回1本书和1篇文章:

for $x in doc("xmldata.xml")/library
where $x/article/author = 'John Doe' 
where $x/book/author = 'John Doe'
return ($x/article/title, $x/book/title)

有人能帮帮我吗?也许是指着我正确的方向或指出我出错的地方。

完整的XML文件:

<library>
 <book>
  <author>John Doe</author>
  <title>Turnitin</title>
 </book>
 <article>
  <author>John Doe</author>
  <title>Evaluating</title>
 </article>
 <article>
  <author>Shannon, L.</author>
  <title>Reconceptualising</title>
 </article>
 <book>
  <author>Burden, David</author>
  <title>An evaluation</title>
 </book>
 <article>
  <author>Moscrop, C.</author>
  <title>Evaluating a systematic method</title>
 </article>
 <book>
  <author>Beaumont, C.</author>
  <title>Beyond e-learning</title>
 </book>
</library>

2 个答案:

答案 0 :(得分:0)

抱歉,我错过了你要查询的路径。只有一个库元素,因此您的for循环只迭代一次,然后由于至少有一个 <author>匹配您的where子句,它返回了所有来自<library>的值。

解决方案是在层次结构中向下迭代一级:

for $x in doc("xmldata.xml")/library/*
where $x/author = 'John Doe' 
return $x/title

或者,如果您想清楚选择哪些元素:

for $x in doc("xmldata.xml")/library/(article|book)
...

要控制不同元素的值输出,您可以在返回时使用不同的XPath:

...
return ($x/self::book/title, $x/self::article/author)

答案 1 :(得分:0)

您可以使用通配符*来匹配元素,无论其名称如何:

doc("xmldata.xml")/library/*[author = 'John Doe']/title

这相当于更详细的FLWOR表达式

for $entry in doc("xmldata.xml")/library/*
where $entry/author = 'John Doe'
return $entry/title
相关问题