How To Use Xpath Syntax To Select XML Nodes

In this blog, I am demonstrating different syntaxes of XPATH on selecting nodes using expression and steps.
 
I will be using this below XML file as a reference to my demo.
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <TrainingData>  
  4.   
  5.   <Courses name=".net">  
  6.       <Training name="c# basic">  
  7.           <content name="data types" hours="1"></content>  
  8.           <content name="events and delegates" hours="2"></content>  
  9.       <price>100</price>  
  10.       </Training>  
  11.       <Training name=".net core">  
  12.           <content name="REST API" hours="2"></content>  
  13.           <content name="MVC" hours="2"></content>  
  14.       <price>200</price>  
  15.       </Training>  
  16.       <Training name="VB">  
  17.           <content name="data types" hours="1"></content>  
  18.       <price>50</price>  
  19.       </Training>  
  20.   </Courses>  
  21.   
  22.   <Courses name="Javascript">  
  23.     <Training name="basics">  
  24.           <content name="data types" hours="1"></content>  
  25.       <price>100</price>  
  26.       </Training>  
  27.   </Courses>  
  28.   
  29.   <Courses name="non technical">  
  30.     <Training name="negotiation skills">  
  31.       <price>60</price>  
  32.     </Training>  
  33.     <Training name="7 habits">  
  34.       <price>70</price>  
  35.     </Training>  
  36.   </Courses>  
  37.   
  38.   <Others>  
  39.     <Training name="Time managment">  
  40.       <price>0</price>  
  41.     </Training>  
  42.   </Others>  
  43.     
  44. </TrainingData>  
Let's read the file first and get the XDocument object to use XPath syntax. 
  1. static void Main(string[] args)  
  2. {  
  3.     var location = new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath;  
  4.     var path = Path.GetDirectoryName(location);  
  5.     var filePath = args.Any() ? args[0] : Path.Combine(path, "..you path of xml\\Trainingdata.xml");  
  6.   
  7.     if (!File.Exists(filePath))  
  8.     {  
  9.         throw new InvalidOperationException();  
  10.     }  
  11.   
  12.     var document = XDocument.Load(filePath);  
  13. }  
Let's start with XPath syntax one by one to select nodes based on your requirement.
 
Selecting Nodes
 
Select all Courses and trainings nodes using '//' symbol for all elements.
  1. //select all Courses Node irrespective of where it is defined.  
  2. document.XPathSelectElements("//Courses");  
  3.   
  4. //select all training node irrespective of where it is defined.  
  5. document.XPathSelectElements("//Training");  
Select root node course by using the '/' symbol.
  1. var rootcourse = document.XPathSelectElement("TrainingData/Courses");    
  2.     
  3. // select the current node by '.' symbol, here root as current node.    
  4. var selectingcurrent = rootcourse.XPathSelectElements("./Training[@name='c# basic']");    
  5.   
  6. // select all tranings under .net course  
  7. var firstCourse = document.XPathSelectElement("//Courses[@name='.net']");  
  8. var alltrainings = firstCourse.XPathSelectElements("./Training");  
Reading multiple elements
 
Select all others and non technical trainings use '//' for all elements and for union use '|' sysmbol.
  1. document.XPathSelectElements("//Courses[@name = 'non technical'] | //Others");  
Predicates (indexing, last(), @, *)
 
Select the first course (using the index or last() etc predicates).
  1. document.XPathSelectElements("//Courses[1]");  
  2.  // same way can be done for last "//Courses[last()]"  
Using @
  1. // select all content node having hour attribute, @ symbol used for attribute.  
  2. var hourAttribite = document.XPathSelectElements("//content[@hours]");  
  3.   
  4. // select all content node having hour=2 attribute.  
  5. var hour2Attribite = document.XPathSelectElements("//content[@hours = 2]");  
Using node name direclty
  1. // select all tranings whose price >= 100.  
  2. var trainingpricegreat100 = document.XPathSelectElements("//Training[price >= 100]");  
Using *
  1. // select all conent having name as datatype.  
  2. // use '*' to match any type of node where name is equal to data type  
  3. var hourAttribite = document.XPathSelectElements("//*[@name='data types']");  
  4. // OR  
  5. var allconenthaveDatatype = document.XPathSelectElements("//content[@name='data types']");  
I hope you liked this blog. The code is attached with a performance test. Let me know any questions you might have in the comments section.
Thanks!
Next Recommended Reading Deserialize XML with Array Node In C#