选择“至少2”XPath表达式

时间:2014-04-04 03:21:14

标签: sql expression xquery

我需要编写一个XPath表达式,根据下面的数据查找至少有2个供应商的城市(表达式应该返回Chicago和Madison,因为他们每个都有2个供应商):

<SuppliersList>
  <Supplier name="Joe">
    <City>Paris</City>
    <Product name="Airplane"/>
    <Product name="Milk"/>
    <Product name="TV"/>
    <Product name="Orange"/>
 </Supplier>
  <Supplier name="Herman">
    <City>Chicago</City>
    <Product name="Orange"/>
 </Supplier>
 <Supplier name="Bernstein">
    <City>Madison</City>
    <Product name="Truck"/>
    <Product name="TV"/>
  </Supplier>
 <Supplier name="Hunter">
    <City>Wausau</City>
  </Supplier>
  <Supplier name="Mayer">
    <City>Madison</City>
  </Supplier>
  <Supplier name="Rosenfeld">
    <City>Chicago</City>
    <Product name="Computer"/>
    <Product name="Book"/>
    <Product name="Truck"/>
  </Supplier>
</SuppliersList>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

//Supplier[City = following::Supplier/City]/City

说明:

  • 获取所有Supplier元素
    • 其中City元素等于当前节点下的任何Supplier/City元素
  • 并使用City元素

当然,在XSLT模板中这更容易

修改

现在我看到你正在使用XQuery,而不是XPath:

DECLARE @x xml
SET @x = '
<SuppliersList>
  <Supplier name="Joe">
    <City>Paris</City>
    <Product name="Airplane"/>
    <Product name="Milk"/>
    <Product name="TV"/>
    <Product name="Orange"/>
 </Supplier>
  <Supplier name="Herman">
    <City>Chicago</City>
    <Product name="Orange"/>
 </Supplier>
 <Supplier name="Bernstein">
    <City>Madison</City>
    <Product name="Truck"/>
    <Product name="TV"/>
  </Supplier>
 <Supplier name="Hunter">
    <City>Wausau</City>
  </Supplier>
  <Supplier name="Mayer">
    <City>Madison</City>
  </Supplier>
  <Supplier name="Rosenfeld">
    <City>Chicago</City>
    <Product name="Computer"/>
    <Product name="Book"/>
    <Product name="Truck"/>
  </Supplier>
</SuppliersList>'
SELECT @x.query('
    let $cities := //City
    for $city in distinct-values($cities)
        where count($cities[. eq $city]) >= 2
        return $city
    ')