Free Web Development Online Tutorials, Learn to Code
Learn MVC C#, How to read data from xml in MVC c#

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();
doc.Load(xmlpath); 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 | Core Tutorial