XQuery合并重复的XML结构

时间:2016-04-10 12:12:13

标签: xml xslt xquery

我试图弄清楚如何将“代码”相同的下面的任何重复结构合并。我想总结代码匹配的number_of_units和value_of_units元素。另外,在结果集中保留不同的“书籍”,即代码T101将保留在下面的示例中。任何帮助将不胜感激。

<book_breakdown>
        <book>
           <name>Life of Pi</name>
           <code>T348</code>
           <unit_price>
              <price currency='GBP'>11.99</price>
           </unit_price>
      <unit_holding>
              <number_of_units>14</number_of_units>
              <value_of_units>159.92</value_of_units>
        <unit_holding>
        </book>
        <book>
           <name>Catcher in the rye</name>
           <code>T101</code>
           <unit_price>
              <price currency='GBP'>10.99</price>
           </unit_price>
             <unit_holding>
              <number_of_units>14</number_of_units>
              <value_of_units>159.92</value_of_units>
        <unit_holding>
        </book>
      <book>
           <name>Life of Pi</name>
           <code>T348</code>
           <unit_price>
              <price currency='GBP'>11.50</price>
           </unit_price>
       <unit_holding>
              <number_of_units>13</number_of_units>
              <value_of_units>129.92</value_of_units>
        <unit_holding>
        </book>
     </book_breakdown>

1 个答案:

答案 0 :(得分:2)

您可以使用fn:distinct-values(...)获取所有唯一的code,然后从中重建文档:

<book_breakdown>{
  for $code in distinct-values(//book/code)
  order by $code
  let $books := //book[code = $code]
  return <book>{
    $books[1]/(name, code),
    <unit_price>{
      (: do something sensible with differing/matching prices here :)
      $books/unit_price/price
    }</unit_price>,
    <unit_holding>
      <number_of_units>{sum($books//number_of_units)}</number_of_units>
      <value_of_units>{sum($books//value_of_units)}</value_of_units>
    </unit_holding>
  }</book>
}</book_breakdown>

这导致以下文件:

<book_breakdown>
  <book>
    <name>Catcher in the rye</name>
    <code>T101</code>
    <unit_price>
      <price currency="GBP">10.99</price>
    </unit_price>
    <unit_holding>
      <number_of_units>14</number_of_units>
      <value_of_units>159.92</value_of_units>
    </unit_holding>
  </book>
  <book>
    <name>Life of Pi</name>
    <code>T348</code>
    <unit_price>
      <price currency="GBP">11.99</price>
      <price currency="GBP">11.50</price>
    </unit_price>
    <unit_holding>
      <number_of_units>27</number_of_units>
      <value_of_units>289.84</value_of_units>
    </unit_holding>
  </book>
</book_breakdown>