Friday, September 23, 2011

Reading Local XML File in Silverlight







When you want to read variables from an xmlfile in Silverlight, you place that xml file in the same folder as you XAML files so that it will get embedded into your XAP file.
The Silverlight program will always grab the xml file that is within the XAP file, even if you have a local copy. You can't just change the path to point to the local copy.

If you want to read a LOCAL xmlfile instead, you have to download it into the XAP file during runtime.

To read a local copy of xmlfile, and therefore include local changes on that file in your Silverlight program, you have to do two things:

1.

Write a procedure that uses the Webclient, as follows:

void GetLocalXML()

{

WebClient client = new WebClient();

client.DownloadStringCompleted += new ;

DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

Uri url = new Uri(LocalXMLFile, UriKind.Relative);

client.DownloadStringAsync(url); }



The LocalXMLFile is a string variable that holds the path/name of the xml file. You can just directly enter the path/name.

Notice that this procedure calls the next procedure when it finishes the download.



2.

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

{

if (e.Error == null)

{

StringReader stream = new StringReader(e.Result);

XmlReader reader = XmlReader.Create(stream);

while (reader.Read())

{
// do your code here

}

reader.Close();

}

}

Total Pageviews