3

I have to find out the second Supplier with Chicago as the city.

I have the following table created.

CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_XPathQueryTable VALUES(
    '<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>');

I have to find out the second supplier with Chicago as the city.

I have tried the following code and a few variations:

SELECT XMLColumn.query('/SuppliersList/Supplier/City[text()="Chicago"]/../Supplier[2]')
FROM Tb_Supplier

When I use the above code without the /Supplier[2] it shows both of the suppliers with Chicago.

The output is supposed to have

  <Supplier name="Rosenfeld">
    <City>Chicago</City>
    <Product name="Computer"/>
    <Product name="Book"/>
    <Product name="Truck"/>
  </Supplier>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Wisco Gold
  • 65
  • 6
  • 1
    I have to find out the second supplier with Chicago as the city. I had it posted half way down, sorry – Wisco Gold Dec 07 '17 at 00:44
  • This question is very - uhm - related to [this one](https://stackoverflow.com/q/47664562/5089204)... – Shnugo Dec 07 '17 at 09:54

1 Answers1

2

This XPath,

(/SuppliersList/Supplier[City="Chicago"])[2]

will select the second Supplier with "Chicago" as the City, as requested.

kjhughes
  • 106,133
  • 27
  • 181
  • 240