Free Web Development Online Tutorials, Learn to Code
Learn MVC C#, MVC Tutorial for Beginners, Model View Controller

How to read data from xml to C# object

Now we see how to read data from xml to custom object in MVC, Let's say you have some data in XML to be consumed in your MVC application

Create a XML structure with some data
<?xml version="1.0" encoding="utf-8" ?>
<blog title="My Blog Title 1"

<![CDATA[ Blog 2 details

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!

Asp.Net MVC C# Examples | Join Asp.Net MVC Course