XQuery 添加了一个空格,我不明白为什么。我有以下简单的查询:
declare option saxon:output "method=text";
for $i in 1 to 10
return concat(".", $i, "	", 100, "
", ".")
我用 Saxon (SaxonEE9-5-1-8J 和 SaxonHE9-5-1-8J)运行它:
java net.sf.saxon.Query -q:query.xq -o:result.txt
结果如下:
.1 100
. .2 100
. .3 100
. .4 100
. .5 100
. .6 100
. .7 100
. .8 100
. .9 100
. .10 100
.
我的问题来自于点之间存在额外的空格。第一行没问题,但接下来的行(2 到 10)有这个空格,我不明白为什么。我们看到的数字之间的空格实际上是由字符引用插入的表格。
你能告诉我这种行为吗?
PS:即使问题不是特定于撒克逊语,我也添加了撒克逊语作为问题的标签。
我认为您的查询返回一系列字符串值,然后默认情况下用空格连接(请参阅http://www.w3.org/TR/xslt-xquery-serialization/#sequence-normalization,其中显示“对于 S2 中相邻字符串的每个子序列,将单个字符串复制到新序列,该字符串等于按顺序连接的子序列中的字符串的值,每个字符串之间用一个空格分隔”)。如果你不想这样,那么你可以使用
string-join(for $i in 1 to 10
return concat(".", $i, "	", 100, "
", "."), '')
点之间的空间基本上是您正在构建的序列中的项目之间引入的分隔符。看起来 Saxon 的文本序列化器在输出到控制台时会插入空格字符,以便您能够理解输出项。
考虑你的代码:
declare option saxon:output "method=text";
for $i in 1 to 10
return
concat(".", $i, "	", 100, "
", ".")
for $i in 1 to 10 return
的结果是一个由 10 个 xs:string 项组成的序列。从您的输出中,您可以确定空格散布在 concat(".", $i, "	", 100, "
", ".")
的每个评估之间。
如果您想检查是否可以将查询重写为:
for $i in 1 to 10
return
<x>{concat(".", $i, "	", 100, "
", ".")}</x>
您将看到 10 个不同的项目,彼此之间没有空格。
如果您尝试创建单个文本字符串,因为您已经控制了换行符,那么您还可以自己将所有 10 个 xs:string 项连接在一起,这将具有消除您看到的空格的效果序列项之间。例如:
declare option saxon:output "method=text";
string-join(
for $i in 1 to 10
return
(".", string($i), "	", "100", "
", ".")
, "")
item-separator
,可以在查询序言中指定:
xquery version "3.0";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "text";
declare option output:item-separator "";
for $i in 1 to 10
return "."||$i||"	"||100||"
"||"."
(由于此解决方案依赖于 XQuery 3.x,因此我冒昧地将
concat
函数的使用替换为 ||
字符串连接运算符。)
结果(两点之间没有空格):
.1 100
..2 100
..3 100
..4 100
..5 100
..6 100
..7 100
..8 100
..9 100
..10 100
.