How to read a local XML file in Silverlight and to read a XML file in Silverlight and bind its data?

SheoNarayan
Posted by in Silverlight category on for Beginner level | Points: 250 | Views : 32147 red flag

In this article, we are going to learn working with data in SilverLight.

Working with Data in Silverlight

Data is the back bone of any Line of Business application and in this section we are going to learn about working with data in Silverlight.

How to read a local XML file in Silverlight?

To read XML file in Silverlight, we can either user XmlReader or LINQ to XML, in this example we are going to learn LINQ to XML.

This article is the continuation of my last article in Silverlight controls series, read last article here.

Get 500+ ASP.NET web development Tips & Tricks and ASP.NET Online training here.

XML File (kept under ClientBin folder of the Silverlight hosting application)

<?xml version="1.0" encoding="utf-8" ?>

<People>

<Person FirstName="Ram" LastName="Sita"/>

<Person FirstName="Krishna" LastName="Radha"/>

<Person FirstName="Heer" LastName="Ranjha"/>

</People>

In the above code we have a XML file with People as parent node and then we have several Person node that has person’s details.

Code

<Button Content="Read Local XML File" Click="Button_Click_1"/>

<sdk:DataGrid x:Name="DataGrid1" AutoGenerateColumns="True" /> 

In the above code snippet, we have a Button and on click of button we are calling Button_Click_1 server side method.

Code behind

private void Button_Click_1(object sender, RoutedEventArgs e)

{

WebClient client1 = new WebClient();

client1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client1_DownloadStringCompleted);

Uri filePath = new Uri("XMLFile1.xml", UriKind.Relative);

client1.DownloadStringAsync(filePath);

}

void client1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

{

if (e.Error == null)

{

XDocument doc = XDocument.Parse(e.Result);

IEnumerable<Person> list = from p in doc.Descendants("Person")

select new Person

{

FirstName = (string)p.Attribute("FirstName"),

LastName = (string)p.Attribute("LastName")

};

DataGrid1.ItemsSource = list;

}

}

public class Person

{

public string FirstName { get; set; }

public string LastName { get; set; }

} 

In the above code snippet we have created a Person class based on the schema of the XML file (properties corresponding to the attributes of each Person node).

On click of the button, we are instantiating WebClient class and setting the event handler for DownloadStringCompleted that calls client1_DownloadStringCompleted method when the download of the file attached with this client object is complete.

We are calling the DownloadStringAsync method by passing the file name to download. Here our file name is XMLFile1.xml that exists into the ClientBin folder of the Silverlight hosting application.

When the download of this file completes, client1_DownloadStringCompleted method fires that provided us an opportunity to retrieve the result or any error occurred.

In this method we are checking for Error object and if it is null we are using XDocument class (exists into System.Xml.Linq namespace) to parse the Result and then using LINQ query to retrieve each Person node and setting its value into Person class. This LINQ query shall give us IEnumerable object.

At last we are setting the ItemsSource property of the DataGrid to this list IEnumerable object.

Output

How to read a XML file in Silverlight and bind its data?

To read the RSS feed in Silverlight, we can follow this approach.

Code

<Button Content="Read RSS Feed" Click="Button_Click"/>

<sdk:DataGrid x:Name="DataGrid1" AutoGenerateColumns="True" /> 

In the above code snippet, we have a Button and a DataGrid. On click of the button, we are calling Button_Click event.

Code behind

// read rss feed

private void Button_Click(object sender, RoutedEventArgs e)

{

string rssFeed = "http://feeds.feedburner.com/ItfundacomTutorialsFeed?format=xml";

WebClient client = new WebClient();

client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

Uri feed = new Uri(rssFeed, UriKind.RelativeOrAbsolute);

client.DownloadStringAsync(feed);

}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

{

if (e.Error == null)

{

XmlReader reader = XmlReader.Create(new StringReader(e.Result));

SyndicationFeed feed = SyndicationFeed.Load(reader);

reader.Close();

IEnumerable<MyFeed> feedList = from f in feed.Items

select new MyFeed

{

Title = f.Title.Text,

Description = f.Summary.Text,

Link = f.Links.FirstOrDefault().ToString()

};

DataGrid1.ItemsSource = feedList;

}

else

{

TextBlock1.Text = "Sorry, an error occured . " + e.Error.ToString();

}

}

public class MyFeed

{

public string Title { get; set; }

public string Description { get; set; }

public string Link { get; set; }

}

We need to use System.Xml, System.IO, System.ServiceModel.Syndication namespace.

In the above code snippet, we have a MyFeed class that corresponds to the different items elements of the RSS feed.

Button_Click

On click of the Button, we are instantiating the WebClient class and then setting client_DownloadStringCompleted method with the DownloadStringCompleted event of this object then we are calling the DownloadStringAsyn method by passing the uri of the RSS feed.

client_DownloadStringCompleted

In this method, we are checking for Error and if it is null then using the XmlReader to read the RSS feed result & then loading SyndicationFeed with the help of this reader. SyndicationFeed is an object that is used to read ATOM or RSS feeds.

Once we have the SyndicationFeed we are using LINQ query to get the items of this feed into the IEnumerable collection and then setting it to the DataSource of the DataGrid.

Output

Hope this article was useful. Thanks for reading and hoping that you liked it.

Keep an eye on forth coming articles on Silverlight. To read my series of articles,click here.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)