MarkLogic:XQuery从XML文档中获取不同的名称?

时间:2016-04-11 23:00:02

标签: xml xquery marklogic

我使用以下文件:

<bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

我使用以下查询从XML文档中获取名称

for $x at $i in doc("bookstore.xml")/bookstore/book/*
return fn:distinct-values(name($x))

我得到以下结果:

title
author
year
price
title
author
year
price
title
author
author
author
author
author
year
price
title
author
year
price

相反,我只想要一个如下所示的独特的一个。

title
author
year
price

我相信我弄乱了for循环。有人可以帮我解决这个问题吗?我尝试使用distinct-values()。没有运气。

3 个答案:

答案 0 :(得分:4)

您在for循环中调用distinct-values(),对于表达式返回的序列中的每个项目调用一次。而是将for表达式的结果传递给distinct-values()

fn:distinct-values(
  for $x at $i in doc("bookstore.xml")/bookstore/book/*
  return name($x)
)

一方注意:node-name()local-name()通常建议超过name()。当您需要元素的qualified name时使用前者,而当您只需要字符串值时使用后者。

答案 1 :(得分:4)

name($x) contains name of element that currently referenced by variable $x. And $x always references one element at a time, so calling distinct-values() on name($x) won't be useful. Instead, you want to call distinct-values() on a collection containing all the elements name, like for example :

let $result := 
    for $x at $i in doc("bookstore.xml")/bookstore/book/*
    return name($x)
return fn:distinct-values($result)

This can also be achieved using plain XPath expression as follow :

distinct-values(doc("bookstore.xml")/bookstore/book/*/name(.))

答案 2 :(得分:0)

您也可以尝试最简单的

let $x := doc("bookstore.xml")/bookstore/book
return distinct-values($x/name())