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