How to read data from xml to C# object

Here you learn how to read from xml in MVC, reading xml document using c#.

Let's say you have some data in XML file, to be consumed in your application, So you need to read data from xml to custom object in MVC application.

Step 1:
Create a XML structure with some data.

<?xml version="1.0" encoding="utf-8" ?>
<blog title="My Blog Title 1"

<![CDATA[ Blog 2 details

Step 2:
Let's create an object called blogObj

public class blogObj
public string title { get; set; }
public string shortinfo { get; set; }
public string imagePath { get; set; }
Read xml data into custom object

Now we write a function that will read data from xml and populate the custom object collection

public static List<blogObj> GetBlogList(string xmlpath)           
    List<blogObj> obList = new List<blogObj>();
    XmlDocument doc = new XmlDocument();
    XmlNodeList elemList = doc.GetElementsByTagName("blog");
    blogObj _obj = null;           
    foreach (XmlNode chldNode in elemList)
    _obj = new blogObj();
    _obj.title = chldNode.Attributes["title"].Value;
    _obj.imagePath = chldNode.Attributes["imageUrl"].Value;
    _obj.shortinfo = chldNode.InnerText;
    return obList;

Now simply call the method “GetBlogList” wherever you want in your controller, this will read the data from xml file and load into your custom object list.

look at the example below
public ActionResult index() {
List<blogObj> blogList = GetBlogList(Server.MapPath("~/configfiles/homepage.xml"));
ViewBag.BlogList = blogList; return View(); }

Your custom object list is populated with data from XML, Enjoy!

Read data from xml to C# object
Aspnet MVC Training MVC tutorials, learn model view controllers with c#, develop database driven web application using MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Core Tutorial