Binding XML File to Data Grid in Silverlight

No.of Views1280
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  28 Apr 2011 09:04:08
Tag : Silver Light and XAML , Data Binding
In this article, I have tried to demonstrate this with simple steps. What all we are going to do is Download content of XML file as string using WebClient class,Parse XML file using LINQ to XML and Bind parsed result as item source of Data Grid.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

It is a common scenario when we need to bind or display data from XML File to 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 XML file as string using WebClient class.
2.    Parse  XML file using LINQ to XML
3.    Bind parsed result as item source of Data Grid.

Prepare Data Source

Put your XML File in ClientBin folder.   You can put XML file at any server location but in that case you will have to provide absolute URI of the XML file while downloading or reading 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 click event of the Button, Data from XML file will get bind to 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>

DownLoad Data from XML File

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

 

Image Loading

Do not forget to include namespace System.Net to work with 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 xml file , we have written below function .

Image Loading

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 descendants 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 XML File. I am going to create a class Student with properties exactly as the same of attributes of Student Element in XML file.

Student .cs

namespace SilverlightApplication5
{
    public class Student
    {
 
        public string RollNumber { get; set; }
        public string Name { get; set; }
 
    }
}

For reference 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,

 

Image Loading

That's all, hope help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top