Free Web Development Online Tutorials, Learn to Code
Learn Asp.net MVC C#, Asp.net 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 Asp.net MVC, Let's say you have some data in XML to be consumed in your asp.net MVC application


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

<![CDATA[  Blog 2 details
]]>
</blog>
</blogs>

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;

    obList.Add(_obj);
    }

    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!

Comment
Name
Email
Website
Subscribe