Loading a static XML file to your Windows Phone/Silverlight App

So I think I’ve mentioned before I have been working on a Windows Phone 7 application. It’s been a real learning experience as oftentimes as a writer, I get to know my feature areas very well, but don’t create full-blown applications using several features. How to load a static xml file into my application is one of the things I’ve recently learned.

In my application, I have a fair amount of static data that lends itself to an XML file very well…it’s not enough data for a database solution, but too much to hard-code into the app. My goal was to store the info in an xml file and load it into an LINQ XElement.  Then I could easily use LINQ queries to get the data I needed into my application. Unfortunately, it took a bit of messing around to figure out how to load this data from the file. Following are the steps I took.

First, I created my xml file outside of Visual Studio, but you could easily create it using Visual Studio. Either way you need to add the file to your project either by adding an existing item or a new item. You do this by right-clicking the project and selecting "Add Existing Item” or “Add New Item” from the context menu.

image

If you choose New Item, select “XML File” and then add your content to the file. If you’ve already created the file, select “Existing Item” and browse the file system to find and select the file you need.

Here are the important steps:

In Solution Explorer, right-click the xml file and choose “Properties”. Using the drop-down, change the “Build Action” to “Resource”.

image

Then, in the code, use the static Application.GetResourceStream to load the file into a stream that in turn, can be loaded into an XElement. You are loading an xml file that is considered a resource (as indicated by the build action), relative to the application package (.XAP file). To locate the resource, the GetResourceStream method takes a Uri that is built using a combination of the project name and the xml file name, with “component” stuck in the middle. The syntax is like the following:

StreamResourceInfo xml =
Application.GetResourceStream(new Uri(“/projectname;component/xmlfilename.xml”, UriKind.Relative));

So for my project, which is called WindowsPhoneApplication1 and an xml file named data.xml, here’s my code:

 using System.Xml.Linq;

// Declare an XElement to hold the contents of the xml file. 
XElement appDataXml;

// Get a stream to the XML file which contains the data and load it into the XElement. 
StreamResourceInfo xml = 
  Application.GetResourceStream(new Uri("/WindowsPhoneApplication1;component/data.xml", UriKind.Relative)); 
appDataXml = XElement.Load(xml.Stream);
 The file loaded beautifully and I was off to my next problem.
 --Cheryl