2

在 XQuery 3.0 中,如何检测由 return 子句生成的最后一个分组后元组(由XQuery 3.0 规范定义)?是否可以使用类似的东西position() = last()position该函数的上下文是什么?

例如,假设我想通过 XQuery 生成 CSV 输出。为了分隔 CSV 输出中的行,我在return子句生成的每个元组之后附加一个换行符:

xquery version "3.0";

declare option saxon:output "omit-xml-declaration=yes";
declare option saxon:output "method=text";

declare variable $data := (
    <items>
        <item>
            <property name="a"/>
            <property name="a"/>
            <property name="b"/>
        </item>
        <item>
            <property name="a"/>
        </item>
        <item>
            <property name="b"/>
            <property name="c"/>
            <property name="d"/>
        </item>
        <item>
            <property name="b"/>
            <property name="c"/>
        </item>
    </items>
);

for $item in $data/item,
    $name in $item/property/@name
group by $name
return (
    text{string-join(($name, string(count($item))), ",")},
    text{"&#10;"}
)

但是,这会在最后一个元组之后留下一个空行。如果我可以测试元组的位置,我可以避免在最后一个元组之后添加换行符。

4

1 回答 1

2

The XQuery specs indeed seem to be missing something like group by $variable at $position here, similar what would be allowed in the for clause. Reading up the XQuery 3.0 specs again, I couldn't find anything that would help, either. position() and last() require a node context, which is not available within loops.

But regarding your underlying problem: why not use another string-join(...) to concatenate the items with newlines in-between, similar to like you did for the counts?

string-join(
  for $item in $data/item,
      $name in $item/property/@name
  group by $name
  return (
      text{string-join(($name, string(count($item))), ",")}
  ),
  text{"&#10;"}
)
于 2015-02-06T17:11:28.050 回答