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>

Down Load 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.

clip_image002

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 .

clip_image004

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,

clip_image006

Advertisements

3 thoughts on “Binding XML File to Data Grid in Silverlight

  1. Hi there,

    Great post there for a beginner like me! Got an issue though:

    I uploaded the Data.xml to my host@ http://www.ptm.asia/xml/Data.xml

    but I seem to read it:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.Xml.Linq;
    using System.Xml;

    namespace SilverlightApplication10
    {
    public partial class MainPage : UserControl
    {
    List 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(“http://www.ptm.asia/xml/Data.xml”, UriKind.Absolute);
    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();

    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;
    }

    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s