Tuesday, November 8, 2011

Binding WPF DataGrid with XML File using XmlDataProvider

In this article I will demonstrate how to bind xml file with WPF datagrid.

There are several ways to achieve this but in this post i will demonstrate using XMLDataProvider to load and bind xml file to WPF Data Grid. XmlDataProvider exposes Source and XPath properties. Source property can be used to provide xml file name while XPath property used to specify the element name to generate collection.

Let’s have a look on below example.

XML File – CustomerData
<?xml version="1.0" encoding="utf-8" ?>
  <Customer Name="Mitesh Sureja" Address="Address1"
            City="Mumbai" Phone="443322" />
  <Customer Name="Parag Kumar" Address="Address2"
            City="New Delhi" Phone="558652" />
  <Customer Name="Kalyan S" Address="Address3"
            City="Bangalore" Phone="654821" />
  <Customer Name="Subrata Banerjee" Address="Address4"
            City="Calcutta" Phone="225566" />
  <Customer Name="Rama K" Address="Address5"
            City="Chennai" Phone="998855" />
  <Customer Name="Jigar Seth" Address="Address6"
            City="Ahmedabad" Phone="774411" />

<Window x:Class="WpfApplication1.DataGridAndXMLData"
        Title="DataGrid With XmlData" Height="200" Width="300">
        <XmlDataProvider Source="Data\CustomerData.xml"
                         XPath="Customers" x:Key="custData" />
        <DataGrid Name="CustomerGrid" AutoGenerateColumns="False"
                  ItemsSource="{Binding Source={StaticResource custData},XPath=*}">
                <DataGridTextColumn Binding="{Binding XPath=@Name}"
                                    Header="Name" />
                <DataGridTextColumn Binding="{Binding XPath=@Address}"
                                    Header="Address" />
                <DataGridTextColumn Binding="{Binding XPath=@City}"
                                    Header="City" />
                <DataGridTextColumn Binding="{Binding XPath=@Phone}"
                                    Header="Phone" />


As demonstrated in above example, XmlDataProvider loads CustomerData.xml file. Data Grid’s Item source property is bind with custData key and each column is bind with XPath. The similar thing can also be achieved using LinqToXML(XLINQ).

See Also –


  1. Thank you, this was exactly what I was looking for :D

  2. Best implementation of wpf extended datagrid can be found here WPF Extended DataGrid

    Project Description

    This is extended version of WPF toolkit DataGrid control.

    This grid has features like

    1:Column Choosers.
    2:AutoFilter Control.
    3:Export To Excel Feature.
    4:Copy Paste To Excel and Copy Paste From Excel 5:To DataGrid.
    6:Three State Sorting.
    7:Displaying Sort Order If Multiple Sort is done