Object serialization to XML

In this recipe, we shall explore how to serialize an object and then deserialize the XML back to an object.

Getting ready

Open a new Phone 7 application project and save it as Recipe5_SerializeXml. Press F5 and make sure it compiles without any errors.

How to do it...

In the following steps, we will create sample data to save and serialize it to XML. We will then open it using the deserialize method and then display it in a list box.

  1. Open the MainPage.xaml file; add a button to trigger the saving and opening of the serialization. The XAML should look like the following code snippet:
    <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="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResourcePhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="Serialize Xml" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Margin="12,146,12,0" Grid.Row="1">
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="213*" />
    <ColumnDefinition Width="243*" />
    </Grid.ColumnDefinitions>
    <ListBox x:Name ="lstTasks" Margin="0,6,0,198" Grid.ColumnSpan="2">
    <ListBox.ItemTemplate>
    <DataTemplate>
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
    <RowDefinition Height="15" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="150" />
    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>
    <TextBlockGrid.Row="0" Grid.Column="0" Text=" {Binding Name}" FontWeight="Bold" Foreground="OrangeRed"/>
    <TextBlockGrid.Row="0" Grid.Column="1" Text="{BindingDateDue}" />
    <TextBlockGrid.Row="0" Grid.Column="2" Text="{Binding Priority}" Foreground="Yellow"/>
    <TextBlockGrid.Row="1" Grid.ColumnSpan="3" Text="{Binding Notes}" />
    <TextBlockGrid.Row="2" Grid.ColumnSpan="3" />
    </Grid>
    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>
    </Grid>
    <Button Content="Save and Load Xml" Height="72" HorizontalAlignment="Left" Margin="24,48,0,0" Name="button1" VerticalAlignment="Top" Width="423" Grid.Row="1" Click="button1_Click" />
    </Grid>
    
  2. Add the button1_Click event method.
  3. Press F5 and the resulting page should look like the following screenshot:
    How to do it...
  4. Let's add a new class file and modify the MyTask class by adding serialization attributes as shown in the following code snippet. Here, ElementName indicates what name to use when creating the root XML element. The XmlElement attribute indicates each of the properties being used as attribute elements:
    [XmlRootAttribute(ElementName="MyTask",IsNullable=false)]
    public class MyTask
    {
    [XmlElement]
    public string Name { get; set; }
    [XmlElement]
    public string Notes { get; set; }
    [XmlElement]
    public string Priority { get; set; }
    [XmlElement]
    publicDateTimeDateDue { get; set; }
    [XmlElement]
    publicDateTimeDateCreated { get; set; }
    }
    
  5. Add a reference to the assembly System.Xml.Serialization of the project and then add the using declaration to the MainPage.xaml.cs file.
  6. Now add a method SaveXmlToLocalStorage to save the XML to local storage:
    Private void SaveXmlToLocalStorage()
    {
    List<MyTask>iTasks = new List<MyTask>
    {
    newMyTask(){Name = "Task Name 1",Notes = "Task Details 1", Priority = "High", DateDue = DateTime.Parse("7/01/2011"), DateCreated=DateTime.Now},
    newMyTask(){Name = "Task Name 2",Notes = "Task Details 2", Priority = "Low", DateDue = DateTime.Parse("10/01/2011"), DateCreated=DateTime.Now},
    newMyTask(){Name = "Task Name 3",Notes = "Task Details 3", Priority = "Medium", DateDue = DateTime.Parse("12/11/2011"), DateCreated=DateTime.Now}
    };
    XmlSerializerxmlSerializer= new XmlSerializer(typeof(List<MyTask>));
    using (IsolatedStorageFileisFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
    using (IsolatedStorageFileStreamxmlStream = isFile.OpenFile(@"streamXmlFile.xml", System.IO.FileMode.OpenOrCreate))
    {
    xmlSerializer.Serialize(xmlStream, iTasks);
    }
    }
    xmlSerializer= null;
    }
    
  7. Add another method called LoadXmlFromLocalStorage() to deserialize the XML file from the local storage:
    Private void LoadXmlFromLocalStorage()
    {
    List<MyTask>iTasks = newList<MyTask>();
    XmlSerializerxmlSerializer= new XmlSerializer(typeof(List<MyTask>));
    using (IsolatedStorageFileisFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
    if (isolatedStorage.FileExists(@"streamXmlFile.xml"))
    {
    using (StreamReader reader = new StreamReader(isolatedStorage.OpenFile (@"streamXmlFile.xml", FileMode.Open)))
    {
    iTasks = xmlSerializer.Deserialize(reader) asList<MyTask>;
    }
    }
    }
    lstTasks.ItemsSource = iTasks;
    xmlSerializer= null;
    }
    
  8. Now let's call the preceding two methods, SaveXmlToLocalStorage() and LoadXmlFromLocalStorage()in the button click event method:
    private void button1_Click(object sender, RoutedEventArgs e)
    {
    SaveXmlToLocalStorage();
    LoadXmlFromLocalStorage();
    }
    
  9. Press F5 and click on the Save and Load Xml button. You should be able to serialize the sample XML to local storage and retrieve it back to display in the list box control. The result should look like the following screenshot:
    How to do it...

How it works...

Initially we used the object initializer to create some test XML data as a list. Then we created the XmlSerializer object. Similar to recipes in Chapter 2, Isolated Storage, we opened the isolated storage XMLstream for creating the file and saving it. Then we used the Serialize method to write the XML document to a file called streamXmlFile.xml using the stream object.

Once the XML file is created in the local storage, we can use the same procedure as saving to open the file. While reading the XML file, we first check if the file exists in the isolated storage, then using the StreamReader object we open the file using the property FileMode.Open. We then deserialize the reader objects and convert them to a list collection.

There's more...

For more detailed information about the XmlSerializer class refer to the MSDN article at the following link: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx.

In the Chapter 7, Windows Communication Framework, we discuss how to consume WCF (Windows Communication Foundation) web services. In WCF, the default serializer used is DataContractSerializer. You can learn more on this topic at the following link: http://msdn.microsoft.com/en-us/library/ms731073.aspx.

You can also serialize to JSON (Java Script Object Notation) using DataContractJsonSerializer. You can learn more about this class at the following link: http://msdn.microsoft.com/en-us/library/system.runtime. serialization.json.datacontractjsonserializer(v=vs.95).aspx.

Also, you can use the WCF attribute ResponseFormat=WebMessageFormat.Xml for XML format or ResponseFormat=WebMessageFormat.Json for JSON format.

See also

XML is not the only way to save information to local storage. Refer to Chapter 5, Using On-Device Databases, and you will learn how to save information using On-Device database options. Also, check Chapter 7 to learn more on WCF.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset