如何为XQuery循环创建正确的语法

时间:2011-10-07 01:54:59

标签: xml xslt xquery

现在我有一个dita复合材料,如:

<root>
 <topic>....</topic>
 <topic>....</topic>
 <topic>....</topic>
 <topic>....</topic>
 <topic>....</topic>
</root>

我只需要编写一个xquery,基本上会为每个主题创建一个ditamap,所以重新推出的ditamap应该是这样的:

<map>
 <topicref>....</topicref>
 <topicref>....</topicref>
 <topicref>....</topicref>
 <topicref>....</topicref>
 <topicref>....</topicref>
</map>

我当前的Xquery不是很正确,它可以捕获每个主题,但不是创建一个ditamp,而是创建多个ditamap,每个主题一个:

 $isFoSaved := for $b in $mapNode/*[local-name() = 'topic']
               let                                     
               $topicWithPI := let $holder:=1
               return (
                      <topicref href="1.xml#Begin" navtitle="Begin" scope="local" type="topic"/>
                ),  

专家能帮忙吗?谢谢

2 个答案:

答案 0 :(得分:1)

我只能看到你正在嵌入多个flwor表达式。

每当您使用$x := let $y ...$x := for $y ...时,您都会启动一个新的flwor表达式,该表达式必须由return子句关闭。因此,您剪断的代码无效/不完整:您有两个打开的flwor表达式,但只有一个return子句。

如果你试图让它保持平坦,那就容易多了。

例如:

<map>{
 let $mapNode := 
   <root>
     <topic>....</topic>
     <topic>....</topic>
     <topic>....</topic>
     <topic>....</topic>
     <topic>....</topic>
    </root>
  for $b in $mapNode/*[local-name() = 'topic']
  return 
    <topicref href="1.xml#Begin" 
              avtitle="Begin"
              scope="local" 
              type="topic"/>
}</map>

此查询适用于try.zorba-xquery.com,但我不确定这是否是您要找的内容?

答案 1 :(得分:1)

如果您想保留嵌套主题的层次结构,则会更复杂一些。我认为最好使用递归函数:

declare function local:topicref($topics)
{
  for $b in $topics
  return 
    <topicref href="1.xml#Begin" 
              avtitle="Begin"
              scope="local" 
              type="topic">{
      local:topicref($b/*[local-name() = 'topic'])
    }</topicref>

};

<map>{
 let $mapNode := 
   <root>
     <topic><topic>....</topic></topic>
     <topic>....</topic>
     <topic>....</topic>
     <topic>....</topic>
     <topic>....</topic>
    </root>
 return 
   local:topicref(
     $mapNode/*[local-name() = 'topic']
   )
}</map>

结果:

<?xml version="1.0" encoding="UTF-8"?>
<map>
  <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic">
    <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic"/>   
  </topicref>
  <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic"/>
  <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic"/>
  <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic"/>
  <topicref href="1.xml#Begin" avtitle="Begin" scope="local" type="topic"/>
</map>