Using Xml Files on Windows Phone

The Windows Phone does not have a database for you to use locally on the phone. This means that you will need to use WCF services to get data from a database. However, each time you make a call to a WCF service this means that you need to connect to the network, make a call to a remote service, get the data back and put it into a format that you can consume on the phone. All of this takes time, and just as important, consumes battery power. If you have some data that is fairly static you could deploy that data with your application in the form of an XML file. With the XML file deployed on the phone as a part of your application, you use LINQ to XML to read the data. That data can now be displayed in any format you choose.

This article assumes that you have Visual Studio 2010 and the Windows Phone tools installed along with it. The Windows Phone tools must be downloaded separately and installed with Visual Studio2010. You may also download the free Visual Studio2010 Express for Windows Phone developer environment.

Use Xml Files to Store Static Data on Windows Phone
Figure 1: Use XML Files to Store Static Data on Windows Phone

The Product Xml File

For this example, you will use a simple XML file filled with some product data. Let’s assume that this data does not change very often. Below is the sample Product.xml file.

<Products>
  <Product ProductId="1"
           ProductName="PDSA .NET Productivity Framework"
           IntroductionDate="3/3/2002"
           Price="20000" />
  <Product ProductId="2"
           ProductName="Architecting ASP.NET Applications eBook"
           IntroductionDate="4/3/2002"
           Price="19.95" />
  <Product ProductId="3"
           ProductName="Haystack Code Generator for .NET"
           IntroductionDate="7/1/2010"
           Price="19.95" />
  <Product ProductId="4"
           ProductName="Security for ASP.NET Developers eBook"
           IntroductionDate="8/25/2004"
           Price="19.95" />
</Products>

When you add an XML file to your project, be sure to change the Build Action in the Properties window to “Content” in order to have this file deployed with the application.

The Product Class

It is a best practice to always load data into a class when being used in a program. This allows for strong typing and for automatic data binding on XAML. Below is a Product class that has a property that corresponds to each attribute of the Product element in the Product.xml file.

public class Product
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public DateTime IntroductionDate { get; set; }
  public decimal Price { get; set; }
}

Reading the Xml File

Now that you have the XML file and the Product class you are now ready to read this data from within your Windows Phone application. Create a new Windows Phone application. On the MainPage.xaml file add a ListBox in the Content Panel.

<ListBox Name="lstData"
         ItemsSource="{Binding}"
         DisplayMemberPath="ProductName" />

Also, create a Loaded event procedure by adding the appropriate attribute in the phone:PhoneApplicationPage xaml at the top of this file.

Loaded="PhoneApplicationPage_Loaded"

Now, write the following code within the MainPage.xaml.cs Loaded event procedure:

private void PhoneApplicationPage_Loaded(object sender,
 RoutedEventArgs e)
{
  var xElem = XElement.Load("XML/Product.xml");

  var products =
      from elem in xElem.Descendants("Product")
      orderby elem.Attribute("ProductName").Value
      select new Product
       {
       ProductId =
          Convert.ToInt32(elem.Attribute("ProductId").Value),
       ProductName = elem.Attribute("ProductName").Value,
       IntroductionDate =
          Convert.ToDateTime(
            elem.Attribute("IntroductionDate").Value),
       Price = Convert.ToDecimal(elem.Attribute("Price").Value)
       };

  lstData.DataContext = products;
}

The above code is basic LINQ to XML code. You first use the XElement  class to load the Product.xml file from the XML folder in the project. The XElement class is in the System.Xml.Linq namespace so you will need to add a “using” statement at the top of the class in order to use this class.

Once the file is loaded into the XElement object you can now use LINQ to XML to retrieve all descendants named Product. Add an “orderby” clause to sort the data by the ProductName attribute. In the select statement you will tell LINQ to create a new instance of a Product class for each Product element in the XML file. You then use the elem.Attribute method to retrieve the value of each attribute in the current Product element and place that value into the appropriate property of the Product object. After the LINQ query is complete you end up with an IEnumerable collection of Product objects. You can then assign this collection to the DataContext of the ListBox.

Summary

The technique demonstrated in this article will help you reduce the amount of network traffic you generate on your Windows Phone application. In addition, you will also reduce the battery power required for your application to operate. Both of these are great goals to strive for in a phone application. While you won’t be able to use XML files for data that constantly changes, for things like state codes and country codes, using XML files is a great way to go.

NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Using XML Files on the Windows Phone" from the drop-down.

Good Luck with your Coding,
Paul Sheriff

** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1.

Past Blog Content

Blog Archive

6 Comments

Comments have been disabled for this content.