How to Bind XML Data in WPF DataGrid using Dataset and List?

How to Bind XML Data in WPF DataGrid using Dataset and List?

In this tutorial I will try to bind XML data in WPF DataGrid by using Dataset and List. Lets say you have XML file from which you have to read data and show in the WPF datagrid. You can do this task by two methods.

Method 1: Using Dataset

In this approach, I wll read XML file into a dataset and then make a dataview from that dataset and then I will assign that dataview to datagrid. Following is the simple C# code for this.

 private void BindGridUsingDataSet()
 {
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     DataSet dataSet = new DataSet();
     dataSet.ReadXml(sampleXmlFile );     
     DataView dataView = new DataView(dataSet.Tables[0]);
     dataGrid1.ItemsSource = dataView;
 }


Method 2: Using List

I will load XML file into XElement and then I will go on adding all the elements into list and finally I will bind the list to the datagrid. Have a look at following C# code for this.

class college
{
   public string name { get; set; }
   public string roll { get; set; }
   public string marks { get; set; }
}

private void BindGridUsingList()
{
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     XElement xElement = XElement.Load(sampleXmlFile);
     IEnumerable students = xElement.Elements();
     List lstCollege = new List();
     // Read the entire XML
     foreach (var student in students)
     {
          lstCollege.Add(new college {name=student.Element("name").Value,roll=student.Element("roll").Value,marks=student.Element("marks").Value});
     }    
     dataGrid1.ItemsSource = lstCollege;
}


Here is the code of datagrid in XAML file


    
        
        
        
    



Here is the sample XML file

 
      ABC
      12
      90
 
  
     XYZ
     13
     98