Different ways to access XML data in Silverlight Application

One of the most common requirement in the Silverlight development is to load XML data in to the application. I am going to describe a few different options that we can choose based on the situations. I am using LINQ for the XML parsing in the examples. Taking a sample XML file names Sample.xml with the following content

<Employees>
<Employee Name="John"/>
<Employee Name="Mark"/>
<Employee Name="David"/>
</Employees>

1. Load XML file directly from the Web Server hosted Silverlight XAP

You can host the XML file at your web server itself and Silverlight application can load it on demand. To simulate this in Visual Studio you need to create a Test Website for your Silverlight application and put xml file into the ClientBin folder.

image

Now we can write few lines of code to read the XML. WebClient will download the file asynchronously

void Page_Loaded(object sender, RoutedEventArgs e)
{
WebClient xmlClient = new WebClient();
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(XMLFileLoaded);
xmlClient.DownloadStringAsync(new Uri("Sample.xml", UriKind.RelativeOrAbsolute));
}
void XMLFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
string XmlString = e.Result; // Got all your XML data in to a string
XDocument elem = XDocument.Load(XmlReader.Create(new StringReader(XmlString)));
var collection = from nod in elem.Descendants("Employee")
select nod.Attribute("Name").Value;
lstBox.ItemsSource = collection ; // XML data bind to the UI
}

2. Load XML file directly from the Silverlight App(XAP)

image

Add the XML file as a content to the Silverlight project. This is the easiest way to build and deploy a Silverlight project, since you really don't need to worry about the XML file once it is placed as part of the project. When you compile, it will automatically embed the XML file inside the XAP file. But the big problem is that you can’t easily change the XML data after the deployment. . And here the C# to read data from this situation

 XDocument elem = XDocument.Load("Sample.xml");
var collection = from nod in elem.Descendants("Employee")
select nod.Attribute("Name").Value;

3. Load XML file from one of the Silverlight Assemblies

When you have more than one Silverlight class libraries associated with a Silverlight application, it may be meaningful to add the XML file to a different project than the main project. So this case you need to add the file as an EmbeddedResource.

image

  Stream stream = this.GetType().Assembly.GetManifestResourceStream("XmlLoadingTest.Sample.xml");
XDocument elem = XDocument.Load(XmlReader.Create(stream));
var coll = from nod in elem.Descendants("Employee")
select nod.Attribute("Name").Value;

4. Load XML file from a URI

This is the case of accessing third party data from feeds and services. It is a big security threat to access resources from a server where the XAP file didn't not originate. So the server you are requesting access needs a special permission files hosted. You can read more about this here-Making a Service Available Across Domain Boundaries) and here-Network Security Access Restrictions in Silverlight 2

When coming to read this kind of hosted XML urls from C#, you can use either step(1) or step(2) of the above C# code snippets. I prefer the step(1) option because it is asynchronous and will not hang up the UI. And also it will not make the XAP size larger with larger XML files, so the initial loading will be faster.

Comments

Unknown said…
Jobu, it is a good artilce for Silverlight startes. I just wnat to know whether it is possble to update the xml elements dynamically?
OurTie said…
Great article! I was fuzzy on server vs. local xml access and this spelled it out very well. If you have a large dynamic xml file though, you would host it on the server. Of course you would not want to download the whole file every time you accessed it so how would you have the server do the lookup on it and return the results for Silverlight?
Jobi Joy said…
For both of the questions above needs a Web Service to update or partial reading of XML
Nice to see such detailed information Silverlight Application.Silverlight Development Company I found one company called SpadeWorx and they claim that they are leading Flex Development Company in India.
Rakesh said…
Hi How can I update the xml that I have loaded in XDocument elem? What I am trying to do is to display a couple of strings parsed from xml and then add one more string to the xml file. I assusme that my xml file is placed in client bin folder.

Thanks
Rakesh
Jobi Joy said…
@Rakesh Since the file is part of the Webserver, you cant write back from silverlight. You need to have a web service or Webserver code behind to do any XML write operation.
Rakesh said…
HI Jobi,
Yeah I know I have to Update in Webservice. I am using LINQ to XML class in my webservice.. This is my code snippet

XElement po = XElement.Load("WikiXMLdata.xml", LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);

po.Element("Books").Add(new XElement("Book", new XAttribute("ISBN", "hello"),
new XElement("title", "Raksh"), new XElement("Author", "me")));
po.Save("WikiXMLdata.xml", SaveOptions.None);

It throws me an exception when I try to load the contents itself. I believe I am making mistake in loading the xml file in Client bin folder. Can you please help me out how to save the file back with updated Information.

Thank you,
Rakesh
Jobi Joy said…
Hi Rakesh,
When you put something in clientBin it is loading from the server so you need to use Option-1 I mentioned in the blog. So while saving it is not possible to write something back to Server from your Silverlight app. Looks like you tried to use Option-2 which will work only when you add XML as part of your Silverlight project.
Unknown said…
Hi Jobi,
I am exactly using the same Option I you mentioned in your reply. The COde snippet I sent you earlier was in the service only. My question is I am trying to add some data to the downloaded one in webclient. So, can you please show me how to update the xml which is in the client bin folder?
Jobi Joy said…
the short answer is, You cant write to the XML file in clientbin from Silverlight.
Unknown said…
Hi Jobu,
Can you please show a sample of the save function using Web Srvices? I am not able to do it at all.

Thank you,
Rakesh
Jobi Joy said…
XDcoument.Save is the way to go. Sorry that I dont have time to create sample for you.
chaitanya said…
heyy jobu..thnx alot..it worked

Popular posts from this blog

Time Picker User Control

A simple Multiselect ComboBox using expression Blend

A Simple Radial Panel for WPF and SilverLight