Load an XML File Into a WPF DataGrid

How to Load an XML File into a WPF DataGrid. The ReadXml method reads an XML file and loads it into a DataSet.

I just wrote a small article on Loading an XML file into a Windows Form's DataGridView Control but got a question on how to do the same in WPF. Here is another related article : Save Data from a DataGridView to XML.

In this article, we will see how to load an XML into a WPF DataGrid control. If you have not worked with the DataGrid control, I recommend reading DataGrid in WPF.

In ADO.NET, the DataSet class implements methods and properties to work with XML documents. 

The ReadXml method reads an XML file and loads it into a DataSet. ReadXml is an overloaded method; you can use it to read a data stream, TextReader, XmlReader, or an XML file and store it into a DataSet object, that can later be used to display the data in a tabular format. 

The following code snippet loads the Books.xml file into a DataSet. 

  1. DataSet dataSet = new DataSet();  
  2.   
  3. dataSet.ReadXml(@"C:\Books\Books.xml");   
The following code snippet binds the default DataTable with a DataGridView control. 
  1. dataGrid1.ItemsSource = dataSet.Tables[0].DefaultView;   
NOTE:  Make sure you add a reference to the System.Data namespace before using DataSet in your code. 

Sample 

Use the following procedure to create the sample: 

  • Create a WPF application using Visual Studio 2012
  • Add a DataGrid Control to the Window
  • Add a Button control then double-click on it and add the following code to the button click event handler. 
  1. DataSet dataSet = new DataSet();  
  2. dataSet.ReadXml(@"C:\Books\Books.xml");  
  3. dataGrid1.ItemsSource = dataSet.Tables[0].DefaultView;  

The output will be a DataGrid displaying the contents of an XML file. 

 Load-XML-in-WPF-DataGrid1.png

Stay tuned. In my next articles, I will show how to add, update, and delete a XML file data from a DataGrid control.