How To Select XML Node By Name In C#

Let’s first establish what the purpose of the code is in the first place.

For this, the purpose of the code is to "How to select XML node by name in C#". We use MVC (C#) to create this demo.

We use XPath expression to select XML node.

What is XPath?

XPath is a path expression to select the nodes or node-sets in an XML document.

Code

Now, we have the XML document given below. Save it as demo.XML.

  1. <info>  
  2.   <collage>  
  3.     <name>SIGMA INSTITUTE</name>  
  4.     <students>650</students>  
  5.   </collage>  
  6.   <collage>  
  7.     <name>ORCHID INSTITUTE</name>  
  8.     <students>1200</students>  
  9.   </collage>  
  10. </info>  
We want to get all <collage> nodes. Thus, our XPath Expression is "/info/collage".

Create ActionResult Method shown below.
  1. public ActionResult Index()  
  2. {  
  3.     try  
  4.     {  
  5.         //Create A XML Document Of Response String  
  6.         XmlDocument xmlDocument = new XmlDocument();  
  7.   
  8.         //Read the XML File  
  9.         xmlDocument.Load("D:\\demo.xml");  
  10.   
  11.         //Create a XML Node List with XPath Expression  
  12.         XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/info/collage");  
  13.   
  14.         List<Info> infos = new List<Info>();  
  15.   
  16.         foreach (XmlNode xmlNode in xmlNodeList)  
  17.         {  
  18.             Info info = new Info();  
  19.             info.CollageName = xmlNode["name"].InnerText;  
  20.             info.Students = xmlNode["students"].InnerText;  
  21.   
  22.             infos.Add(info);  
  23.         }  
  24.   
  25.         return View(infos);  
  26.     }  
  27.     catch  
  28.     {  
  29.         throw;  
  30.     }  
  31. }   
Create the class given below & declare the properties.
  1. public class Info  
  2. {  
  3.     public string CollageName { get; set; }  
  4.   
  5.     public string Students { get; set; }  
  6. }   
Create a view.
  1. @model IEnumerable<SelectXMLNode.Controllers.HomeController.Info>  
  2.   
  3. @{  
  4.     Layout = null;  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>Index</title>  
  13. </head>  
  14. <body>  
  15.     <div>  
  16.         @if (Model.Count() > 0)  
  17.         {  
  18.             foreach (var item in Model)  
  19.             {  
  20.                 <div class="row">  
  21.                     <div class="col-md-6">Collage: @item.CollageName </div>  
  22.                     <div class="col-md-6">Number Of Students: @item.Students</div>  
  23.                 </div>  
  24.             }  
  25.         }  
  26.     </div>  
  27. </body>  
  28. </html>  
Hence, everything has been done.