Read Data From XML in ASP.Net MVC 5

This article shows how to use XML in a project and also use the basic Class Library helper. 

Prerequisites
  • Visual Studio 2013 (download Express edition to: Visual Studio Express )
  • Bootstrap 3.0 (Download using Nuget Package inside the Visual Studio)
  • jQuery 2.1.1 (Download using Nuget Package inside the Visual Studio)
  • Entity Framework 6.1.1 (Download using Nuget Package inside the Visual Studio) 
Let's get started

Assuming you have already installed the Visual Studio 2013, follow the following images and instructions showing how I use XML and build this sample program/demo. I created a project named DemoUsingXML and add XML file to App_Data.

Right-click the App_Data folder then select Add then New Item.
 
add new item
 
On the left panel of Add new item. Select Data then select XML. Name the XML file depending on your naming convention or object name.

In this demo I named it ProductsData.xml.
 
ProductsData xml file
 
After naming the XML file click add. Then you will see the default XML file.
 
 
Now create the product object to the XML file. See the image below.
 
 
Script inside the ProductsData.xml 
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Products>  
  3. <Product>  
  4. <ProductId>1</ProductId>  
  5. <ProductName>Generic Mouse</ProductName>  
  6. <ProductCost>30.00</ProductCost>  
  7. </Product>  
  8. <Product>  
  9. <ProductId>2</ProductId>  
  10. <ProductName>Generic Keyboard</ProductName>  
  11. <ProductCost>20.00</ProductCost>  
  12. </Product>  
  13. <Product>  
  14. <ProductId>3</ProductId>  
  15. <ProductName>Generic Hard Drive</ProductName>  
  16. <ProductCost>100.00</ProductCost>  
  17. </Product>  
  18. </Products>  
Using Class Library Helper

Now let's add our Class Library helper. See the instructions below.

Right-click the Solution in the project then click Add then choose New Project.
 
 
The Add New Project window will pop up. On the left panel of Add New Project Click C# then choose Windows Desktop. In the center of the Add New Project window choose Class Library.

See image below.
 
 
Rename the Class Library depending on your helper and so on. In this demo I named the library Demo.Helper. Now click Ok.

After clicking OK this will show in your project.
 
 
Now let's do the coding part to read the data inside our ProductsData.xml or XML File.

Right-click
the Reference on Demo.Helper Class Library.

Choose Assemblies then framework look for System.Web then click OK.
 
 
I created an external model or properties; see image below.

Also add using System.Xml.Serialization;

To serialize the class to XML.
 

Code inside the product class
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Xml.Serialization; //Add  
  7. namespace Demo.Helper.External.Models  
  8. {  
  9.       /// <summary>  
  10.       /// This class is being serialized to XML.  
  11.       /// </summary>  
  12.       [Serializable]  
  13.       [XmlRoot("Products"), XmlType("Products")]  
  14.       public class Products  
  15.       {  
  16.             public int ProductId { getset; }  
  17.             public string ProductName { getset; }  
  18.             public string ProductCost { getset; }  
  19.       }  
  20. }  
On your our XMLReader Class that we created inside the Demo.Helper Library.

Add this on top of the code, see code below.

using System.Web;//Add References -> Choose assemblies
using System.Data;//Add
using Demo.Helper.External.Models; // This is the External Model that I created. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Web;//Add References -> Choose assemblies  
  7. using System.Data;//Add  
  8. using Demo.Helper.External.Models; // Add  
  9. namespace Demo.Helper  
  10. {  
  11.    public class XMLReader  
  12.    {  
  13.          /// <summary>  
  14.          /// Return list of products from XML.  
  15.          /// </summary>  
  16.          /// <returns>List of products</returns>  
  17.          public List<Products> RetrunListOfProducts()  
  18.          {  
  19.                string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductsData.xml");//Path of the xml script  
  20.                DataSet ds = new DataSet();//Using dataset to read xml file  
  21.                ds.ReadXml(xmlData);  
  22.                var products = new List<Products>();  
  23.                products = (from rows in ds.Tables[0].AsEnumerable()  
  24.                select new Products  
  25.                {  
  26.                      ProductId = Convert.ToInt32(rows[0].ToString()), //Convert row to int  
  27.                      ProductName = rows[1].ToString(),  
  28.                      ProductCost = rows[2].ToString(),  
  29.                }).ToList();  
  30.                return products;  
  31.          }  
  32.       }  
  33. }  
Now the Demo.Helper Library is done. Let us now use the library in our project and display the products that is the XML file or ProductsData.xml.

First create a controller. Right-click Controller folder inside the project.

Click Add then Controller.

To use the Library that we created, Right-click References then choose Solution then check Demo.Helper then click Ok.

 After right-clicking the Controller folder choose Add then choose Controller then choose one of the controllers in this demo; I chose MVC 5 Controller Empty

Click Add.

I named the controller ProductListController.cs, then Right-click the Index Code inline with the ActionResult then choose Add View; see the image below:

If you want to learn more about view, you may check this out. This link might help you: Adding a View.

Inside the view script add the ff. scripts and code. 


Code inside the index.cshtml. 
  1. @{  
  2. ViewBag.Title = "Index";  
  3. Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5. @using Demo.Helper.External.Models;  
  6. @model IEnumerable<Demo.Helper.External.Models.Products>  
  7. <h2>Product List using XML</h2>  
  8. <table class="table table-bordered">  
  9. <tr>  
  10. <th>Id</th>  
  11. <th>Product Name</th>  
  12. <th>Product Cost</th>  
  13. </tr>  
  14. @foreach (var item in Model)  
  15. {  
  16. <tr>  
  17. <td>  
  18. @Html.DisplayFor(modelItem => item.ProductId)  
  19. </td>  
  20. <td>  
  21. @Html.DisplayFor(modelItem => item.ProductName)  
  22. </td>  
  23. <td>  
  24. [email protected](modelItem => item.ProductCost)  
  25. </td>  
  26. </tr>  
  27. }  
  28. </table>  
Add this code inside the controller. In this project ProductListController.


Add the code inside the Index():
  1. public class ProductListController : Controller  
  2. {  
  3. // GET: ProductList  
  4. public ActionResult Index()  
  5. {  
  6. XMLReader readXML = new XMLReader();  
  7. var data = readXML.RetrunListOfProducts();  
  8. return View(data.ToList());  
  9. }  
  10. }  
Then rebuild the project. Hit Cntrl F5.

This will be shown after running the project.
 
Product List using XML
The data from XML is finally displayed. I hope you have learned something.

More blogs to come.

Enjoy! Cheers.

Thank you God Bless...

Up Next
    Ebook Download
    View all
    Learn
    View all