Saturday, December 15, 2007

Basic XPath Query

Consider the following the XML segment

<tests>

  <test title="Sample Test 1">

    <result type="Passed" status="0"/>

    <result type="Failed" status="0"/>

  </test>

  <test title="Sample Test 2">

    <result type="Passed" status="0"/>

    <result type="Failed" status="0"/>

  </test>

  <test title="Sample Test 3">

    <result type="Passed" status="1"/>

    <result type="Failed" status="0"/>

  </test>

  <test title="Sample Test 4">

    <result type="Passed" status="0"/>

    <result type="Failed" status="1"/>

  </test>

</tests>



Note: xdoc in the following example refers to an instance of Xml.XmlDocument that contains this XML document
  • To retrieve all test nodes from this XML Block, we can use the basic XPath query -

    xDoc.SelectNodes("/tests/test")


  • To retrieve all result nodes that have the type attribute set to "Passed",

    xDoc.SelectNodes("/tests/test/result[@type='Passed'")


  • To retrieve all result nodes that have the type attribute set to "Failed" and having a status of "0",

    xDoc.SelectNodes("/tests/test/result[@type='Failed' and @status='0'")


  • To retrieve the second test node, we can use the following query

    xDoc.SelectNodes("/tests/test[position()=2]")




The last one is especially useful if you do not have unique node identifier attributes and need to access the nth item from the node list. Of course, the other alternative is to use a for each loop and skip n-1 items from the top. But this is a far more elegant solution.

No comments: