Bind XML Data to List
In this article, I will explain how to bind XML data to List. Using XDocument of System.Xml.Linq , XML document can be loaded to XDocument by providing url of the XML document. Using IEnumerable, Xdocument descendant can be binded to the list.
Bind XML Data to List
In this article, I will explain how to bind XML data to List. Using XDocument of System.Xml.Linq , XML document can be loaded to XDocument by providing url of the XML document. Using IEnumerable, Xdocument descendant can be binded to the list.
Full code as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
namespace XMLtoList
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Follwoing XDcoument.Load will create XDocument from given XML filename
XDocument db = XDocument.Load("SampleDB.xml");
//Enumerable Descendants in the following code returns a filtered collection of the descendant elements for this element in document order. Only elements have matching System.Xml.Linq.XName are included in the collection.
List
=
(from emp in db.Descendants("employee")
select new Employee()
{
ID = emp.Attribute("id").Value
,
Name = emp.Element("name").Value
,
Department = emp.Element("department").Value
,
Designation = emp.Element("designation").Value
,
Mobile = emp.Element("mobile").Value
,
DateOfBirth = emp.Element("dateofbirth").Value
,
Emailid = emp.Element("emailid").Value
}).ToList
MessageBox.Show("XML to List is converted Successfully");
}
public class Employee
{
public string ID;
public string Name;
public string Department;
public string Designation;
public string Mobile;
public string DateOfBirth;
public string Emailid;
}
}
}
I had attached sample code for reference.