Monday, March 13, 2017

Read XML file and display data using asp.net MVC

In this article I am going to explain how to read XML file and display data using asp.net MVC.


Description:
I have XML of student detail. I want to read this file and display its data.

XML File:
<?xml version="1.0"?>
<students>
  <student>
    <name>Tarun</name>
    <class_Section>X-A</class_Section>
  <roll_no>1234</roll_no>
  </student>
<student>
    <name>Ram</name>
     <class_Section>X-A</class_Section>
  <roll_no>1235</roll_no>
  </student>
<student>
    <name>Rajeev</name>
      <class_Section>X-A</class_Section>
  <roll_no>1236</roll_no>
  </student>
<student>
    <name>Gopal</name>
    <class_Section>X-A</class_Section>
  <roll_no>1237</roll_no>
  </student>
</students>

Implementation:

First of all I have created a class in model.
Model
public partial class Studentdetail
    {
        public int ID { get; set; }
        public string name { get; set; }
        public string class_Section { get; set; }
          public string roll_no { get; set; }
    }

Add controller
Add empty controller to project. In index action method write the code to read xml file and display data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
using System.Xml;


namespace MVC_Project.Controllers
{
    public class defaultController : Controller
    {
        public ActionResult Index()
        {          
            XmlDocument doc = new XmlDocument();
            List<Studentdetail> students = new List<Studentdetail>();
            doc.Load(Server.MapPath("student.xml"));
            foreach (XmlNode node in doc.SelectNodes("/students/student"))
            {
                students.Add(new Studentdetail
                {
                    name = node["name"].InnerText,
                    class_Section = node["class_Section"].InnerText,
                    roll_no = node["roll_no"].InnerText
                });
            }
            return View(students);
        }
    }
}
  
Add view
Add view for index action.

@{
    ViewBag.Title = "Index";
}

<style>
    table tr td{padding:0 20px}
</style>

<table>
    <tr>
        <th>Name</th>
        <th>Class section</th>
        <th>Roll no.</th>
    </tr>
    @foreach (MVC_Project.Models.Studentdetail student in Model)
    {
        <tr>
            <td>@student.name</td>
            <td>@student.class_Section</td>
            <td>@student.roll_no</td>
        </tr>
    }
</table>


No comments:

Post a Comment