Previously I’ve written about how to create data charts using Silverlight. The data was coming from an static array, which is not that useful after all. Now lets see how to use data from an XML file. Bellow you can see an example of the XML file we’ll use. It is as simple as it can be, having pairs of labels and their associated value.

In your Silverlight project, if you try to open directly the XML file using something like XDocument.Load(”Data.xml”) Silverlight will try to find the file inside the XAP file. We could place the XML file inside the XAP file in order to make it work, but when we needed to update the file we would have to change the XAP file (replacing an XML file in a ZIP file)… Instead, we will use an external XML file. We must download the file using a WebClient (the download term applies: remember that Silverlight code runs in the client side, so while accessing you website resources you are accessing remote resources).

The download is asynchronous, so we need to create an event handler to be executed when the XML file download is completed. The XML file is downloaded as a string, so we need to parse it into a XDocument object, in order to manipulate it. The example bellow shows a little bit of LINQ to XML. LINQ (Language Integrated Query) allows you to query several data sources, including XML, Databases, Object collections, etc (even Amazon…). A nice tutorial about LINQ to XML can be found at Scott Guthrie’s blog.
We iterate through the data points present in the XML file and create a list of pairs containing the labels and respective values. After building the dataPoints list, the remaining code is similar to the code I’ve shown you in the Part 1 of these tutorials.

The next and final step will be to use a WCF web service to retrieve the data from an database in order to create a real dynamic chart powered by Silverlight.






Nice blog, Bruno. Thanks for the XML tutorial.