如何检索多个XML兄弟 - SQL Server

时间:2017-02-22 23:46:15

标签: sql-server xml xpath

我已经彻底搜索过,没有找到任何关于如何查询和检索多个XML兄弟姐妹的值的示例或指导。

有很多关于如何检索单个兄弟值的例子。

例如,给定以下XML片段:

<StoreSurvey>
  <AnnualSales>800000</AnnualSales>
  <AnnualRevenue>80000</AnnualRevenue>
  <BankName>United Security</BankName>
  <BusinessType>BM</BusinessType>
  <YearOpened>1996</YearOpened>
  <Specialty>Mountain</Specialty>
  <SquareFeet>21000</SquareFeet>
  <Brands>2</Brands>
  <Internet>ISDN</Internet>
  <NumberEmployees>13</NumberEmployees>
  <Products Type="Bikes">
    <Product>Mountain</Product>
    <Product>Road</Product>
    <Product>Racing</Product>
  </Products>
  <Products Type="Clothes">
    <Product>Jerseys</Product>
    <Product>Jackets</Product>
    <Product>Shorts</Product>
  </Products>
</StoreSurvey>

如果我想检索<AnnualSales>的值,我可以在查询分析器中执行以下语句:

SELECT Survey_untyped.query('/StoreSurvey/AnnualSales') 
FROM Stores;

结果集将正确显示

<AnnualSales>800000</AnnualSales>

但是,如果我想检索<AnnualSales><AnnualRevenue>,该怎么办?我该怎么办?

查询应提供如下结果集:

<AnnualSales>800000</AnnualSales>
<AnnualRevenue>80000</AnnualRevenue>

或者如果除了这些值之外我还想要三个兄弟值“BankName”怎么办?结果集如下所示:

  <AnnualSales>800000</AnnualSales>
  <AnnualRevenue>80000</AnnualRevenue>
  <BankName>United Security</BankName>

有人知道答案吗?

1 个答案:

答案 0 :(得分:2)

此XPath,使用self:: axis

/StoreSurvey/*[self::AnnualSales or self::AnnualRevenue or self::BankName]

将选择

<AnnualSales>800000</AnnualSales>
<AnnualRevenue>80000</AnnualRevenue>
<BankName>United Security</BankName>

来自您的XML。