Loading an XML File into Silverlight - Page 2
       by kirupa  |  27 April 2008

In the previous page, you setup your project and XML file that you will be loading. In this page, we will look at the code needed to load your XML file when you run your Silverlight application.

Adding the Code
First, open Page.xaml.cs in your Silverlight Project. The code you will see is the default that gets generated for you:

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;
 
namespace LoadingXML
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
}
}

What you will do is overwrite all of the code at the public partial class Page() level and below with the following:

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.Windows.Browser;
 
namespace LoadingXML
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
 
LoadXMLFile();
}
 
private void LoadXMLFile()
{
WebClient xmlClient = new WebClient();
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(XMLFileLoaded);
xmlClient.DownloadStringAsync(new Uri("sampleXML.xml", UriKind.RelativeOrAbsolute));
}
 
void XMLFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
string xmlData = e.Result;
HtmlPage.Window.Alert(xmlData);
}
}
}
}

If you press F5 to test your application, you will see your browser launch. After a few short seconds, you will see a browser alert appear with your XML data showing:

[ displaying your XML data as a browser alert ]

Yay! That was exciting....sort of. What I am showing you is that the code you pasted loaded the XML file and put it in a form that you could easily show as a browser alert. Because this tutorial is only about loading the XML data, this is the extent of functionality I will be describing in this article.

With that said, that doesn't mean we are done with this tutorial. Copying and pasting code is not very useful. What is useful is learning why the code works the way it does, and we'll look at that in the next page.

Onwards to the next page!

1 | 2 | 3 | 4




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.