XQuery和空HTML标记

时间:2014-07-28 08:25:22

标签: html xquery exist-db

我正在学习XQuery并尝试了一个温和的复杂示例。查询本身有效,但我没有按照我想要的方式添加HTML。

以下示例有效(在eXist-db XQuery引擎中)

for $current_value in $another_variable//some_tag/@attribute
return 
    <div><h1>{$current_value}</h1>
    {
    for $current_sub_value in $another_variable//some_tag
    where $current_sub_value/@attribute = $current_value
    return <p> { data($current_sub_value/@another_attribute) } </p>
    }
    </div>

但实际上

  • 我想摆脱包装div。
  • 而不是新的 每个子结果的段落(p ... / p)我想简单地说一个 每一个结果后换行符(br)。

所以,预期结果将是这样的:

<h1> ... some text here ... </h1>
some text here ... <br />
another line here ... <br />

然而,无论我尝试过什么,我总是会遇到语法错误。

似乎可以使用{ ... }在封闭的XML标记中声明XQuery。但是,如果XML标记不是在XQuery周围,而是在之前或之后,我该怎么办?

有没有办法告诉XQuery引擎:这里有一些XQuery,这里有一些HTML,只需将它们连接在一起? (XPath函数concat()对我不起作用,导致显示<br />< >肯定会被转义。)

如上所述,我尝试了一些语法,但总是得到错误消息。这是我做的:

测试1/3

for $current_value in $another_variable//some_tag/@attribute
return 
    <h1>{$current_value}</h1>
    {
    for $current_sub_value in $another_variable//some_tag
    where $current_sub_value/@attribute = $current_value
    return <p> { data($current_sub_value/@another_attribute) } </p>
    }

导致:

  执行表达式时发现

错误:   org.exist.xquery.XPathException:错误:XPST0003意外令牌:{[at   第4行,第5栏]

测试2/3

for $current_value in $another_variable//some_tag/@attribute
{
return 
    <h1>{$current_value}</h1>
    for $current_sub_value in $another_variable//some_tag
    where $current_sub_value/@attribute = $current_value
    return <p> { data($current_sub_value/@another_attribute) } </p>
}

导致:

  执行表达式时发现

错误:   org.exist.xquery.XPathException:错误:XPST0003意外令牌:{[at   第2行,第1栏]

测试3/3

for $current_value in $another_variable//some_tag/@attribute
return
    <div>
    <h1>{$current_value}</h1>
    {
    for $current_sub_value in $another_variable//some_tag
    where $current_sub_value/@attribute = $current_value
    return data($current_sub_value/@another_attribute) <br/>
    }

导致:

  

意外令牌:>(期待元素的结束标记   构造函数:div)

2 个答案:

答案 0 :(得分:4)

您基本上想要的是项目序列。在XML中,元素始终具有一个单根节点。因此,例如关于您的段落,<p>something</p>是一个元素,而您想要的输出something<br/>是一系列项目,在这种情况下是字符串和元素。

在XQuery中,序列只是通过paranthesis包装,例如('s', <a/>, 45)是一个序列。

因此,在您的情况下,以下内容应按预期工作:

for $current_value in $another_variable//some_tag/@attribute
return (
  <h1>{$current_value}</h1>,
  for $current_sub_value in $another_variable//some_tag
  where $current_sub_value/@attribute = $current_value
  return (data($current_sub_value/@another_attribute), <br />)
)

答案 1 :(得分:3)

dirkk在解释序列与混合节点方面表现出色。了解区别以及在何处使用它们将为您提供很长的路要走。

但是,eXist-DB的另一个方面是优化。要使内部优化器工作,最好避免使用WHERE短语,而是使用谓词。

例如,采用上面的dirkk解决方案并修改WHERE以使用谓词:

for $current_value in $another_variable//some_tag/@attribute
return (
  <h1>{$current_value}</h1>,
  for $current_sub_value in $another_variable//some_tag[@attribute = $current_value]
  return (data($current_sub_value/@another_attribute), <br />)
)

索引是实现性能的另一个关键。但是,进入使用谓词来处理WHERE上的条件的做法是很好的。有关此主题的更多信息,请访问:http://exist-db.org/exist/apps/doc/tuning.xml

希望这有帮助。