XQUERY 3.0多级SORT / ORDER BY

时间:2017-02-19 16:03:55

标签: xquery-3.0

我在XML文件上有如下XQUERY 3.0,其中包含3个采购订单,包含5个项目:

 for $PurchaseOrder in doc("C:\Users\thebluephantom\Desktop\order.xml")//PurchaseOrder
   order by xs:integer($PurchaseOrder/Item/Quantity) ascending
   return $PurchaseOrder/Items/Item/Quantity

不能按我的意愿返回结果。它有一个典型的嵌套结构,例如

<PurchaseOrders>  
  <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">  
    <Address Type="Shipping">  
      <Name>Ellen Adams</Name>  
      ... 
    </Address>  
      <Address Type="Billing">  
        <Name>Tai Yee</Name>  
        <Street>8 Oak Avenue</Street>  
        ...
    </Address>  
    <DeliveryNotes>Please leave packages in shed by driveway.  </DeliveryNotes>  
    <Items>  
      <Item PartNumber="872-AA">  
      <ProductName>Lawnmower</ProductName>  
      <Quantity>100</Quantity>  
      <USPrice>148.95</USPrice>  
    <Comment>Confirm this is electric</Comment>  
  </Item>  
    <Item PartNumber="926-AA">  
      <ProductName>Baby Monitor</ProductName>  
      <Quantity>20</Quantity>  
      <USPrice>39.98</USPrice>  
      <ShipDate>1999-05-21</ShipDate>  
  </Item>  
</Items>  
 </PurchaseOrder>  
 <PurchaseOrder PurchaseOrderNumber="99505" OrderDate="1999-10-22">  
   ...

我得到3个PO和5个订单项的结果:

<Quantity>100</Quantity>
<Quantity>20</Quantity>
<Quantity>1</Quantity>
<Quantity>1000</Quantity>
<Quantity>1</Quantity>

查看有关分组等的大量教程。我无法确定这是否可行。

1 个答案:

答案 0 :(得分:1)

Order By中的XPath缺少Items轴,因此它不会选择任何内容,而是按文档顺序获取结果。如果更正了XPath,那么将在xs:integer()调用中选择一系列值并将引发错误。

你可以像这样重写它:

for $quantity in 
         doc("C:\Users\thebluephantom\Desktop\order.xml")/PurchaseOrders/PurchaseOrder/Items/Item/Quantity
order by xs:integer($quantity) ascending
return $quantity