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.
- <info>
- <collage>
- <name>SIGMA INSTITUTE</name>
- <students>650</students>
- </collage>
- <collage>
- <name>ORCHID INSTITUTE</name>
- <students>1200</students>
- </collage>
- </info>
We want to get all <collage> nodes. Thus, our XPath Expression is "/info/collage".
Create ActionResult Method shown below.
- public ActionResult Index()
- {
- try
- {
-
- XmlDocument xmlDocument = new XmlDocument();
-
-
- xmlDocument.Load("D:\\demo.xml");
-
-
- XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/info/collage");
-
- List<Info> infos = new List<Info>();
-
- foreach (XmlNode xmlNode in xmlNodeList)
- {
- Info info = new Info();
- info.CollageName = xmlNode["name"].InnerText;
- info.Students = xmlNode["students"].InnerText;
-
- infos.Add(info);
- }
-
- return View(infos);
- }
- catch
- {
- throw;
- }
- }
Create the class given below & declare the properties.
- public class Info
- {
- public string CollageName { get; set; }
-
- public string Students { get; set; }
- }
Create a view.
- @model IEnumerable<SelectXMLNode.Controllers.HomeController.Info>
-
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div>
- @if (Model.Count() > 0)
- {
- foreach (var item in Model)
- {
- <div class="row">
- <div class="col-md-6">Collage: @item.CollageName </div>
- <div class="col-md-6">Number Of Students: @item.Students</div>
- </div>
- }
- }
- </div>
- </body>
- </html>
Hence, everything has been done.