Binding XML File to Data Grid in Silverlight



It is a common scenario when we need to bind or display data from a XML File to a Silverlight Data Grid. In this article, I have tried to demonstrate this with simple steps. What all we are going to do is:

  1. Download content of a XML file as string using the WebClient class.
  2. Parse the XML file using LINQ to XML.
  3. Bind the parsed result as the item source of a Data Grid.

Prepare Data Source

Put your XML File in the ClientBin folder. You can put the XML file at any server location but then you will have to provide an absolute URI of the XML file while downloading or reading the XML file.

I have created a sample Data.xml file:

Data.xml

<?xml version="1.0" encoding="utf-8" ?>
<School>
  <Student RollNumber="1" Name="John Papa" />
  <Student RollNumber="2" Name="Scott Gui" />
  <Student RollNumber="3" Name="Jessy Liberty" />
  <Student RollNumber="4" Name="Tim Huer" />
  <Student RollNumber="5" Name="Victor G" />
  <Student RollNumber="6" Name="Mahesh Chand" />
  <Student RollNumber="7" Name="Pinal Dave" />
  <Student RollNumber="8" Name="Suprotim Agarwal" />
  <Student RollNumber="9" Name="Dhananjay Kumar" />
  <Student RollNumber="10" Name="Kunal Chawudhary" />
  <Student RollNumber="11" Name="Abhijit Jana" />
  <Student RollNumber="12" Name="Shiv Prasad Koirala" />
</School>


Design xaml page

I am going to create a simple page. This page is going to have a Button and a Data Grid. On the click event of the Button, Data from XML file will get bound to the Data Grid.

MainPage.xaml

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
             x:Class="SilverlightApplication5.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Vertical" Margin="50,50,50,50">
        <Button x:Name="btnDemo" Content="Click To get Data From  XML File" Height="62" Width="362" />
       <sdk:DataGrid x:Name="grdXmlData" Height="Auto" Width="Auto" AutoGenerateColumns="True" />
        </StackPanel>         
    </Grid>
</UserControl
>


Down Load Data from XML File

I am using the WebClient class to download the content of the XML file as a string. On the button click event the content of the XML file downloaded.

BindXML1.gif

Do not forget to include the System.Net namespace to work with the WebClient class.

Parse XML Data and bind to Data Grid

We are going to use LINQ to XML to parse data. Include Namespace System.Xml.Linq. To parse data from a xml file, we have written the following function.

BindXML2.gif

Explanation
  1. Function is taking string as input parameter. Here we will pass e.Result from Downloadcompletedstring event.
  2. Creating an instance of XDocument by parsing string
  3. Reading each descendant or element on Xml file and assigning value of each attribute to properties of Entity class (Student).

We need to create an Entity class to map the data from the XML File. I am going to create a class Student with properties exactly as the same of attributes of the Student Element in XML file.

Student .cs

namespace SilverlightApplication5
{
    public class Student
    {
        public string RollNumber { getset; }
        public string Name { getset; }


    }
}


For reference the full source code is as below:

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq; 

namespace SilverlightApplication5
{
    public partial class MainPage : UserControl
    {
        List<Student> lstStudents = null
        public MainPage()
        {
            InitializeComponent();
            btnDemo.Click += new RoutedEventHandler(btnDemo_Click);
        }

        private void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            Uri uritoXML = new Uri("Data.xml"UriKind.Relative);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(uritoXML);

        }


        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                MessageBox.Show("There is Error Downloading Data from XML File ");
            }
            else
            {

                ParseXMLFile(e.Result);
            }
        }

        void ParseXMLFile(string  dataInXmlFile)
        {

            lstStudents = new List<Student>();

            XDocument xmlDoc = XDocument.Parse(dataInXmlFile);
            lstStudents  = (from r in xmlDoc.Descendants("Student")
                         select new Student
                         {
                             Name = (string) r.Attribute("Name").Value,
                             RollNumber =(string) r.Attribute("RollNumber").Value 
                         }).ToList();

            grdXmlData.ItemsSource = lstStudents; 

        }

    }
}


On running we will get output as below:

BindXML3.gif


erver'>
Up Next
    Ebook Download
    View all
    Learn
    View all