【问题标题】:nested looping within Xquery results in a mismatch? and idiomsXquery 中的嵌套循环会导致不匹配?和成语
【发布时间】:2020-12-13 12:08:52
【问题描述】:

我正在玩 w3schools 的 bookstore XML

<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" cover="paperback">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

我使用 XQuery 3.1 查询:

xquery version "3.1";

declare option output:method 'xml';

for $doc in db:open("bookstore")
let $books := $doc/bookstore/book
return(
    for $book in $books
    let $authors := $book/author
    let $title := data($book/title)
    return
    <b>{
    (<t>{$title}</t>,$authors)
    }</b>
)

就目前而言,输出是期望的结果。

查询的嵌套 for 循环是可以理解的,但可能不是“Xquery”-ish?

至少在本例中,一本书只有一个标题,但有多个作者,这可能会导致这里的循环被使用或误用,这可能有点不匹配。

输出:

<b>
  <t>Everyday Italian</t>
  <author>Giada De Laurentiis</author>
</b>
<b>
  <t>Harry Potter</t>
  <author>J K. Rowling</author>
</b>
<b>
  <t>XQuery Kick Start</t>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
</b>
<b>
  <t>Learning XML</t>
  <author>Erik T. Ray</author>
</b>

这个问题本身并不是一个代码审查,更多的是寻找替代或更标准的方法。与上下文不完全无关的切线:

https://martinfowler.com/bliki/OrmHate.html

【问题讨论】:

    标签: xml xpath xquery nested-loops flwor


    【解决方案1】:

    说实话,我不确定您的问题是什么,但您的 XQuery 可以简化很多

    for $book in db:open("bookstore")/bookstore/book
    return <b>
      <t>{string($book/title)}</t>
      {$book/author}
    </b>
    

    这会导致创建相同的节点

    <b>
      <t>Everyday Italian</t>
      <author>Giada De Laurentiis</author>
    </b>
    <b>
      <t>Harry Potter</t>
      <author>J K. Rowling</author>
    </b>
    <b>
      <t>XQuery Kick Start</t>
      <author>James McGovern</author>
      <author>Per Bothner</author>
      <author>Kurt Cagle</author>
      <author>James Linn</author>
      <author>Vaidyanathan Nagarajan</author>
    </b>
    <b>
      <t>Learning XML</t>
      <author>Erik T. Ray</author>
    </b>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多