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" ?>
<Customers>
  <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" />
</Customers>

XAML File
<Window x:Class="WpfApplication1.DataGridAndXMLData"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGrid With XmlData" Height="200" Width="300">
    <Window.Resources>
        <XmlDataProvider Source="Data\CustomerData.xml"
                         XPath="Customers" x:Key="custData" />
    </Window.Resources>
    <Grid>
        <DataGrid Name="CustomerGrid" AutoGenerateColumns="False"
                  ItemsSource="{Binding Source={StaticResource custData},XPath=*}">
            <DataGrid.Columns>
                <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" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Output


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 –

2 comments:

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

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete