Read XML File In ASP.NET MVC

Here, we will learn about reading XML file in ASP.NET MVC. Reading XML file is very important in certain circumstances when the server returns the data in XML format.

We will use the static XML file stored in the local system.

XML File:

<?xml version="1.0"?>  
<Employee>  
    <emp>  
        <id>1</id>  
        <name>Faisal</name>  
        <gender>Male</gender>  
        <mobile>514545</mobile> 
    </emp>  
    <emp>  
        <id>2</id>  
        <name>Bhavdip</name>  
        <gender>Male</gender>  
        <mobile>5431643</mobile>
    </emp>  
    <emp>  
        <id>3</id>  
        <name>Irshad</name>  
        <gender>Male</gender>  
        <mobile>43265436</mobile> 
    </emp>  
    <emp>  
        <id>4</id>  
        <name>Keyur</name>  
        <gender>Male</gender>  
        <mobile>5435431</mobile>
    </emp>  
    <emp>  
        <id>5</id>  
        <name>Tabish</name>  
        <gender>Male</gender>  
        <mobile>432656</mobile>  
    </emp>  
</Employee>

Create a new project in ASP.NET MVC and open the Index.cshtml of the Home folder and add the code in it.

@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("UploadXML", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" id="fileUpload" name="fileUpload" style="float:left" />
    <input type="submit" value="Get User List" />
}

@if (ViewBag.ShowList)
{
    <table class="table table-bordered table-hover">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Mobile</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.Name</td>
                <td>@item.Gender</td>
                <td>@item.Mobile</td>
            </tr>
        }
    </table>
}

Create a new class as UsersVM.cs file in the Models folder.

public class UsersVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Mobile { get; set; }
    }

Code for HomeController.cs file

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (TempData["employeeData"] == null)
            {
                ViewBag.ShowList = false;
                return View();
            }
            else
            {
                List<UsersVM> empList = (List<UsersVM>)TempData["employeeData"];
                ViewBag.ShowList = true;
                return View(empList);
            }
        }
        [HttpPost]
        public ActionResult UploadXML()
        {
            try
            {
                List<UsersVM> empList = new List<UsersVM>();
                var xmlFile = Request.Files[0];
                if (xmlFile != null && xmlFile.ContentLength > 0)
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(xmlFile.InputStream);
                    XmlNodeList empNodes = xmlDocument.SelectNodes("Employee/emp");
                    foreach (XmlNode emp in empNodes)
                    {
                        empList.Add(new UsersVM()
                        {
                            Id = Convert.ToInt32(emp["id"].InnerText),
                            Name = emp["name"].InnerText,
                            Gender = emp["gender"].InnerText,
                            Mobile = emp["mobile"].InnerText
                        });
                    }
                    TempData["employeeData"] = empList;
                }
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index");
            }
        }
    }

Output:

output

6 Comments

  1. Tariq Hameed

    Salam Faisal Pathan.
    how could i do it with sql server. i want to store data in database, but not working for me,

    0
    0
    Reply
    1. Faisal Pathan

      You can save the entire XML body in db.

      0
      0
      Reply
      1. Tariq Hameed

        Request.Files[0] ???? no find

        0
        0
        Reply
  2. Mauricio

    i try but no work becouse “Request.Files[0] no find

    0
    0
    Reply
    1. Faisal Pathan

      please recheck once all code, it will work (make sure the form is submitted using the submit button and multipart/form-data is placed in form element).

      0
      0
      Reply
    2. Mickey Mouse

      Using .net 5.0 and have the same error. (var xmlFile = Request.Files[0];)
      CS1061: “HttpRequest” does not contain a definition for Files and no accessible extension ….

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories