X-Path Queries

X-Path allows you to execute queries against an XML document and retrieves the queried node/nodes. X-Path can be very complex. For a detailed description, see the X-Path specification at http://www.w3c.org.

<Order>
  <Name>Scott Bradley</Name>
  <OrderItems>
    <Item id="1">Lord of the Rings</Item>
    <Item id="2">Star Wars - Episode II</Item>
  </OrderItems>
  <Price>45.90</Price>
</Order>

To query a specific node in the document you can specify the exact path to an element. Each element will be addressed by its name. So to query the name element we use the following query: "/Order/Name" You see that we have to use a slash prior to the element name. The query engine will start at the document root and searches for a node named "Order". If the node is found, it searches for a subnode named "Name".

The second possibility is to tell the query engine to search for all nodes with a specific name. So, to query all nodes with name "Item" we would use the following statement: "//Item" You see that we use a double slash in this case telling the query engine that it should look for all nodes in the document to match the name.

If we want to query an element that is defined multiple times - like the "Item" node in the example above - we can either query for all nodes with name "Item" or we can tell the engine to just return one of the two identified by its index. So, to query the 2nd "Item" node we would use one of the following statements: "/Order/OrderItems/Item[2]" or "//Item[2]"

If we want to query an "Item" node with a special attribute value - for example the one with id = "2" we would use the following query: "/Order/OrderItems/Item[@id='2']" or "//Item[@id='2']" As you can see we can tell the engine to only return the Item node(s) where the attribute named "id" has the value '2'.