Read Local XML File in Windows Phone 7


Introduction

In this article we are going to explore reading an XML file from our Windows Phone application. Further in this article we have to add an XML file to the Windows Phone application and whatever is inside the XML file we will read it programmatically from Windows Phone. In my previous article we have already read an XML file which is through isolated storage, which has been stored inside the isolated storage and will be retrieved from there later but in this XML file it's totally different from the isolated retrieval in this we will take a new XML file and give it a name and we will mention some details which we will read that information later from Windows Phone 7.

We all know that how to make an XML file it doesn't need to explain all about that. In this article we will also learn how to retrieve data from an XML file which is stored locally. In this procedure you have to much care about the path of the XML file which is much sensitive you have to care about it. Further we will see that how it is possible to accomplish such task that we have an XML file inside an Windows Phone application want to read that file. For such kind of implementation you have to follow the steps which is given below.

Step 1 : In this step first of all we have to open a Windows Phone application; let us see how you will open it.

  • Go to Visual Studio 2010
  • File->New->Project
  • Select the template named as Silverlight for Windows Phone
  • Select the Windows Phone application
  • Give it a name as you want  

Step_1fig.jpg

Step_1_2fig.jpg

Step 2 : Further in this step you have to add an XML file; let us see from where you have to add it which is given below.

Go to Solution Explorer.

Select Project and right-click on it.

Step_2_1fig.jpg

Select add new item.

Step_2_2fig.jpg

Select an XML file and give it a name, whatever you want to give.

Step_2_3fig.jpg

Step 3 : In this step you have to add some namespace to the .cs file which is given below and also see from where you will add a reference of System.Xml.linq.dll.

Go to Solution Explorer.

Select the Reference folder and right click on it.

Step_3_1fig.jpg

There is a window open and from where you have to select the System.xml.linq component and add it.

Step_3_2fig.jpg

Now it will show inside your reference folder.

Step_3_3fig.jpg

Step 4 : Let us see what namespaces you have to add which is seen in the figure given below.

Step_4fig.jpg

Step 5 : In this step we will see the code for the XML file which will be retrieved later given below.

Code :

<?xml version="1.0" encoding="utf-8" ?>

<Mybookhistory>

  <identity genre='Computer' publicationdate='12-22-2011' ISBN='978-0470193938'>

    <title>Computer Organization</title>

    <author>

      <first-name>Amit</first-name>

      <last-name>Maheshwari</last-name>

     

    </author>

    <rating>5</rating>

    <price>$34.67</price>

  </identity>

  <identity genre='DreamViewer' publicationdate='02-15-2012' ISBN='978-1933988573'>

    <title>Beggining of Dreamviewer</title>

    <author>

      <first-name>Alok</first-name>

      <last-name>Pandey</last-name>

    </author>

    <rating>5</rating>

    <price>$50</price>

  </identity>

  <identity genre='Client Architecture' publicationdate='10-20-2012' ISBN='978-0735626218'>

    <title>Client and Server</title>

    <author>

      <first-name>Rajesh</first-name>

      <last-name>Tripathi</last-name>

    </author>

    <rating>4.5</rating>

    <price>$29</price>

  </identity>

  <identity genre='Web' publicationdate='10-20-2011' ISBN='978-4758660070'>

    <title>Web Technology</title>

    <author>

      <first-name>Manish</first-name>

      <last-name>Singh</last-name>

    </author>

    <rating>4.7</rating>

    <price>$27</price>

  </identity>

</Mybookhistory>

 

Step 6 : In this step we will see the code for the MainPage.xaml.cs file which is given below.

 

Code :

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Phone.Controls;

using System.Windows.Resources;

using System.Xml.Linq;

using System.Text;
namespace localxml

{

    public partial class MainPage : PhoneApplicationPage

    {

        XElement mb_data;

        public MainPage()

        {

            InitializeComponent();

            StreamResourceInfo SRI = Application.GetResourceStream(new Uri("/localxml;component/mybookhistory.xml", System.UriKind.Relative));

            mb_data = XElement.Load(SRI.Stream);

            this.ManipulationStarted += new EventHandler<ManipulationStartedEventArgs>(MainPage_ManipulationStarted);

        }

        void MainPage_ManipulationStarted(object sender, ManipulationStartedEventArgs e)

        {

            StringBuilder SB = new StringBuilder();

            SB.Append("###################################" + Environment.NewLine);

            SB.Append("Here Are Some Book History which is given below-->" + Environment.NewLine);

            SB.Append("Books-->" + Environment.NewLine);

            var mb = from item

            in mb_data.Elements("mybookhistory")

                        select item;

            foreach (XElement eachmb in mb)

            {
                SB.Append("************************************************" + Environment.NewLine);

                SB.Append("Title--> " + eachmb.Element("title").Value + Environment.NewLine);

                SB.Append("Author--> " + eachmb.Element("author").Value);

                SB.Append(eachmb.Element("author").Element("first-name").Value + " " +

                eachbook.Element("author").Element("last-name").Value + Environment.NewLine);

                SB.Append("Rating--> " + eachmb.Element("rating").Value + Environment.NewLine);

                SB.Append("Price--> " + eachmb.Element("price").Value + Environment.NewLine);

                SB.Append("************************************************" + Environment.NewLine);

            }

            textBlock1.Text = SB.ToString();

        }

    }

}

 

Step 7 : In this step we will see the code for the MainPage.xaml file which is given below.

 

Code :

 

<phone:PhoneApplicationPage

    x:Class="localxml.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"

    FontSize="{StaticResource PhoneFontSizeNormal}"

    Foreground="{StaticResource PhoneForegroundBrush}"

    SupportedOrientations="Portrait" Orientation="Portrait"

    shell:SystemTray.IsVisible="True">
    <!--LayoutRoot is the root grid where all page content is placed-->

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

            <TextBlock x:Name="PageTitle" Text="My Local Xml" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontFamily="Comic Sans MS">

               <TextBlock.Foreground>

                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                    <GradientStop Color="Black" Offset="0" />

                    <GradientStop Color="#FF73D07E" Offset="1" />

                  </LinearGradientBrush>

               </TextBlock.Foreground>

            </TextBlock>

        </StackPanel>
        <!--ContentPanel - place additional content here-->

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <TextBlock Height="555" HorizontalAlignment="Left" Margin="12,25,0,0" Name="textBlock1" Text="Click to see xml file information"

                        VerticalAlignment="Top" Width="438" FontFamily="Comic Sans MS" FontSize="26">

              <TextBlock.Foreground>

                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                    <GradientStop Color="Black" Offset="0" />

                    <GradientStop Color="#FFA1DEE5" Offset="0.648" />

                </LinearGradientBrush>

              </TextBlock.Foreground>

            </TextBlock>

            <Grid.Background>

                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                    <GradientStop Color="Black" Offset="0" />

                    <GradientStop Color="#FFFF59FF" Offset="1" />

                </LinearGradientBrush>

            </Grid.Background>

        </Grid>

    </Grid>
</
phone:PhoneApplicationPage>

 

Step 8 : In this step you will see that if you are changing your class name as MyfirstXml rather than MainPage you can use it as another class name but you have to do some changes by going inside the WMAppManifest.xml; here is the figure (below) where you will write the class name inside that file.

Step_8_1fig.jpg

Step 9 : In this step we will see the design of the MainPage.xaml file which is given below:

designpage.jpg

Step 10 : Now it's time to run the application by pressing F5 and the related output is given below.

Output 1 : It's the default output whenever we run the Windows Phone application.

output1new.jpg

Output 2 : Whenever we will click on the TextBlock then it will show you the content of the XML file which you have inside your XML file.

output2.jpg

Here are  some related resources which is given below.

Reading an Xml file using C#.NetReading and manipulating an Xml file using C#.Net (including images) How to use XML in Windows Phone
Save And Read Data From Isolated Storage in Windows Phone 7