Published: 01 Mar 2011
By: Xianzhong Zhu
Download Sample Code

In this article I will introduce to you how to handle XML data in Windows Phone 7 for Silverlight applications.

Contents [hide]

The Windows Phone 7 Silverlight Programming series

  • Part 1 In this article, we will focus upon MultiTouch and manipulation related operations in Silverlight for Windows Phone programming.
  • Part 2 In this article, we will delve into how to perform navigation operations between pages as well as passing data in a Silverlight for Windows Phone application.
  • Part 3 In this article I will introduce to you how to handle XML data in Windows Phone 7 for Silverlight applications.
  • Introduction

    Data storage and access is nearly an eternal topic in all kinds of applications. In Windows Phone 7, data manipulation still plays a fundamental and important role. Regrettably, in the current Windows Phone 7 Series there is no local database API that can be used. Windows Phone 7, though, does support access to data in several ways: XML, Isolated Storage, and Cloud Storage. In this article I will introduce to you how to handle XML data in Windows Phone 7 for Silverlight applications. In detail, we'll explore three cases: how to load and render a local resource-formed XML file; how to abstract components hidden inside an XAML (XML form in essence) file, and how to obtain remote XML data via a simple RSS reader sample.

    NOTE

    The sample test environments in this article involve:

    1. Windows 7;

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. Windows Phone Developer Tools RTW;

    5. Silverlight for Windows Phone Toolkit at codeplex (http://silverlight.codeplex.com/releases).

    Load a XML File

    XML is a typical and important data form in Windows Phone applications. In this section, we'll discuss a simple yet typical case associated with XML- load and render a local resource-formed XML file. First of all, let's create a sample XML file (or you can select an existing one).

    Create a local XML file

    Start up Visual Studio 2010 and create a general Windows Phone 7 sample project named WP7XML. Then, right click the sample project and select "Add | New Item..." to open the "Add New Item" dialog box. In the dialog select the "XML File" template to create an empty XML file, naming it bookstore.xml.

    Note after adding the XML file we need to change its related Build Action property to Resource in the file properties (see Figure 1). The related explanation is given later on.

    Figure 1: Change the XML file related Build Action property to Resource

    Change the XML file related Build Action property to Resource

    The following indicates the final contents of the XML document bookstore.xml:

    NOTE

    It is important to distinguish the difference between setting the Build Action property of an asset to Content and to Resource in a Windows Phone application. If you set the Build Action property of an asset to Content, it means Visual Studio will copy the related files into the application directory when the program is built. Thus, adding content has no effect on the size of the program itself, although of course when a program is running and loads content it will use more memory. A Resource item is stored in the program assembly. When a Windows Phone device loads a program it looks through the entire program assembly and does some checks to make sure that it is legal code. So, you should be careful about putting too many things in the program assembly.

    Till now, we've created a simple and well-formed XML file. Next, we will continue to learn how to read it out and render it onto the screen.

    Load and read local XML file

    In my previous article at dotnetslackers we mentioned the Application class, which provides a typical site for global data storage. In this case, we are going to use the GetResourceStream method in this class to load the contents of the XML file into a StreamResourceInfo object. The related code is as follows (the sample page is LocalXMLDealingPage.xaml):

    First, to use the namespace System.Xml.Linq we need to manually add reference to the assembly System.Xml.Linq.dll. Second, pay attention to the path in the Uri class "/WP7XML;component/bookstore.xml" (the same form as that in stand Silverlight). In this case, I use Linq to XML to grab the node information in the XML file. We first through the XElement.Load method load the entire XML stream, then in the ManipulationStarted event handler of the page to read out all book information, and finally we assign the result to the Text property of a TextBlock control. In this way, the whole XML tree gets rendered onto the screen.

    Additionally, for XML files, we can also directly obtain XElement by invoking XElement.Load("/WP7XML;component/bookstore.xml"). You can further dig into this yourself.

    OK, now start up the sample page (I've simple modify the line <DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/> in the file WMAppManifest.xml into <DefaultTask Name ="_default" NavigationPage="LocalXMLDealingPage.xaml"/>) and click somewhere on the screen (this will trigger the ManipulationStarted event handler of the page), you will see the entire XML tree rendered out. Below is a screenshot of the sample page.

    Figure 2: Local XML data get rendered

    Local XML data get rendered

    Above we've explored a simple example of loading a local XML tree in Windows Phone 7. In fact, the functionalities in Linq to XML in Silverlight for Windows Phone 7 are far more than this. You can continue to look into how to write XML in Silverlight for Windows Phone 7. Let's next shift our attention to another interesting XML related topic.

    Load Objects in XAML File

    XAML stands for "Extensible Application Markup Language"; it is the language used by Silverlight to describe what a page should look like. XAML looks a lot like XML, which is based on XML syntax to express items and elements and is quite easy to understand.

    In this section, we are going to explore a typical case concerning the XAML data.

    Create simple XAML files

    In real scenarios, we often need to load some UI elements from files or resource, e.g. the UI elements in an XAML file. Now, let's build a simple example to achieve this.

    First, let's prepare an XAML file for read test. We can, of course, create a text file and then rename its extension to .XAML, but the better way is rest upon the quick generating ability of Visual Studio. To do this, follow the steps below:

    1. Right click the sample solution WP7XML and select "Add | New Item..." to open the "Add New Item" dialog box.

    2. Create an arbitrary file with the extension being .xaml, naming it Ellipse.xaml.

    3. Remove the automatically-generated contents, and then add the new contents as follows:

    4. Follow the similar steps above to add another file named it Rectangle.xaml.

    Now, we create two XAML files: one is a circle; the other is a rectangle, setting up their corresponding properties. In the above operation, please do bear in mind to add the appropriate XML namespaces (xmlns) that are corresponding to Silverlight for Windows Phone 7. Creating the XAML files in Visual Studio has the advantage that you can get help from the designer, seeing the effect in real time. Of course, you can also use Expression Blend to do this. Moreover, do not forget to remove the Code-Behind file *.xaml.cs that Visual Studio automatically generates.

    Last but not the least point is do not forget to set the Build Action property of the preceding two files to Resource; or else, running the sample you will catch sight of nothing rendered on the phone.

    Resolve XAML files

    To parse XAML files we need to use the XamlReader class, which provides an important XAML processor engine to analyze XAML and creating corresponding Silverlight object tree. In Silverlight for Windows Phone, it contains only a static Load method; this method is used to parse a well-formed XAML fragment and creates the corresponding Silverlight object tree, and then returns the root of the tree. The method Load accepts a parameter of type string. Although we can pass the code in the XAML file directly to this method, in real-world projects, we usually do not take a hard-coded policy. Instead, we utilized the same method as in the previous section - the GetResourceStream method of the Application class. The result code looks like the following:

    Here I create a generic helper method to return objects of different types. In this method, we use the Application.GetResourceStream method to load the XAML file, and then use StreamReader to read it into a string. At last, we pass this string into the Load method of XamlReader to construct the appropriate type.

    Use the newly-obtained Silverlight objects

    Now that we've got the corresponding objects, the next thing is deal with them on the fly. In this sample, I added two buttons in the program to render two different objects (corresponding to the two XAML file above) on the page. The complete code is as follows.

    The above two buttons related Click event handlers are easy to understand. First, judge whether the Grid tag named ContentPanel contains the target component. If so, remove it and then add the one grabbed out of the related XAML file as a child node to the parent Grid control. If not, just add it. That's all.

    Well, let's now look at the running-time snapshots.

    Figure 3: Load the ellipse object from XAML

    Load the ellipse object from XAML

    Figure 4: Load the rectangle object from XAML

    Load the rectangle object from XAML

    The above sample is much too simple. However, you can continue to extend your idea to dynamically load your well-designed animations, game sprites, and more...

    Create a Simple RSS Reader- Consuming Remote XML Data

    Now, let's take a look at a more realistic sample associated with remote XML data manipulation- a RSS reader. Since our main interest focuses upon the RSS related XML data manipulation, this sample application only provides the following functionalities:

    • Subscribe a new RSS channel
    • List all the items in the RSS channel
    • Displays the feed contents

    First of all, it's necessary to give a simple introduction to RSS data.

    Introduction to RSS

    RSS is a typical XML-based format that allows the syndication of lists of hyperlinks, along with other information or metadata, that helps users decide whether they want to follow the link. Here's an example of a minimal RSS 2.0 feed:

    Listing 1: An example of a minimal RSS 2.0 feed

    Currently, nearly all web sites provide support for RSS 2.0. From the above listing we can see that a RSS file is mainly composed of nodes, such as rss, channel, and item, etc. The following Table 1 list the standard elements that constitute an RSS file.

    Table 1: Standard elements within a RSS 2.0 channel

    Element

    Definition

    Title

    The title of this channel

    Link

    The hyperlink of the web site for the channel to be linked to

    Description

    The description info for this channel

    Language

    (omitted)

    Copyright

    (omitted)

    managingEditor

    (omitted)

    webMaster

    The info of the main manager of the web site

    pubDate

    (omitted)

    lastBuildDate

    (omitted)

    image

    The image info within this channel

    Now that you've gained a fundamental understanding with the typical RSS file scheme. Let's next introduce how to grab the remote RSS data.

    Grabbing RSS Data using WebClient

    Windows Phone applications supports connect to and access remote servers via a variety of connection mechanisms. However, the present version of the network library in WP7 OS does not support direct sockets as those in Microsoft desktop OS. The good news is the Windows phone emulator does bear the same networking abilities as the real device. It can fully leverage the network connectivity of the host PC it is running on. This means that you can test any applications that use the network on your desktop PC.

    Till now, many readers may think of the WebClient class in standard Silverlight. Yes, WebClient is not only an easy to use tool, but also provide support for downloading and uploading Web resources. For more details about WebClient, please refer to MSDN. However, an important thing to remember is only the asynchronous methods are available in Windows Phone 7.

    Although WebClient makes the above things easy, it comes at some hidden cost. WebClient may block your UI thread (callbacks are made on the UI thread, so any file access will block the UI), but if you go the little bit extra and use HttpWebRequest, your UI will not be blocked.

    WebRequest is an abstract base class encapsulating the request/response model for accessing Internet data in the .NET Framework. Compared with the WebClient, the biggest difference is that WebRequest uses a delegate-based asynchronous programming model, whose acts are performed in a background thread. Moreover, only does its request and response deal with the callback code can it interacts with the UI components. WebClient uses an event-based asynchronous programming model, whose invocations are all in the UI thread, so it is simpler to use.

    In this simple example, we'll select to use WebClient since the WebRequest way has to deal with a lot of asynchronous stuff. For brevity, we only list the crucial related code.

    Obviously, to simplify things, we've fallen back upon Microsoft ready-to-use RSS data manipulation encapsulation model in the namespace System.ServiceModel.Syndication. Note to use the namespace System.ServiceModel.Syndication we have first to add related assembly reference from the path <SystemDrive>:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client.

    In the above code, the main components should be XmlReader and the method SyndicationFeed.Load. Subsequently, the detailed implementation associated with XML data resolve and store is achieved in the foreach statement.

    The running-time snapshots

    Now, let's look at the sample UI design and related running-time snapshots. Starting up the sample project WP7RssReader, you will catch sight of the initial screenshot as shown in Figure 5.

    Figure 5: The main interface before loading the RSS data

    The main interface before loading the RSS data

    First, clicking the button View will trigger the related RSS item viewing page (finished via the WebBrowser control in page details.xaml). Second, clicking the button Menu will lead to a little menu pops up, as shown in Figure 6.

    Figure 6: Clicking button Menu leads to a menu pops up

    Clicking button Menu leads to a menu pops up

    Note in the above sample I've used the ContextMenu control in Silverlight for Windows Phone Toolkit. You can, of course, continue to decorate the menu in more detail. And also, you can easily replace it with the commonly-used Popup component shipped with Silverlight for Windows Phone 7 itself to achieve the similar result.

    Next, clicking the menu item Subscribe can invoke the subscription page. Figure 7 indicates the related running-time screenshot.

    Figure 7: Subscribe to a specified RSS channel

    Subscribe to a specified RSS channel

    Clicking the button OK will add the corresponding RSS channel to the Isolated Storage. And, at the same time, the control will return to the main UI. Note, at this time, the UI shows all the RSS items related title and summary. Also note you may wait half a minute or so to see the rendering result. However, hitting the button Cancel will only navigate the control back to the main UI.

    Well, we've talked so much for the RSS reader example. You can download and examine the sample project yourself. As for the Isolated Storage related story, I'll introduce it in another article.

    Summary

    In this article we've learned the basic XML manipulation related topics via related samples. As you've seen, the XAML data are also, in essence, XML data. In this article, we've only explored loading objects from an local XAML file dynamically. In fact, this is also a most commonly-used situation in various kinds of Windows Phone applications. Finally, we've introduced a simple RSS reader sample application. However, we've only scratched the surface, only touching upon the XML data related stuff. For further implementation, please study the downloadable sample yourself.

    The Windows Phone 7 Silverlight Programming series

  • Part 1 In this article, we will focus upon MultiTouch and manipulation related operations in Silverlight for Windows Phone programming.
  • Part 2 In this article, we will delve into how to perform navigation operations between pages as well as passing data in a Silverlight for Windows Phone application.
  • Part 3 In this article I will introduce to you how to handle XML data in Windows Phone 7 for Silverlight applications.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Displaying Notification Messages in a Silverlight Dashboard Application
    In this article we will see how we could display a notification message and further a list of notifi...
    Air Space Issue in Web Browser Control in Silverlight
    Air Space issue is a common issue in Web Browser control in Silverlight and WPF. To explain the issu...
    TextBox Row Filter in Telerik's RadGridView in Silverlight
    If you have come across the JQGrid features, you might have seen the filter row available as the fir...
    Widget Refresh Timer in MVVM in Silverlight
    In this article we'll see how to refresh and disable widgets using the Model View View-Model pattern...
    Develop a Flexible 2.5D Scene Editor Targeting Silverlight RPG Games - Part 2
    In this article, I'm going to introduce to you how to construct such a 2.5D RPG game scene editor th...

    You might also be interested in the following related blog posts


    Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 23: Azure read more
    Telerik Launches RadControls for Silverlight 3 for Line-of-Business Application Development read more
    A Unique Silverlight Viewer for Reporting Services Aimed to Display Reports from Reporting Services in Silverlight Applications. read more
    Silverlight Twitter Client with authentication read more
    WPF Release History : Q2 2009 (version 2009.2.701) read more
    A Bad Idea, EF Entities over WCF read more
    Better XAML By Farr: WPF Line of Business Seminar read more
    WPF / Silverlight: RadChart and BindableLinq read more
    CodeDigest.Com Article,Codes,FAQs - April,2009 read more
    "The security validation for this page is invalid" when calling the SharePoint Web Services read more
    Top
     
     
     

    Please login to rate or to leave a comment.