In this recipe, we shall explore how to serialize an object and then deserialize the XML back to an object.
Open a new Phone 7 application project and save it as Recipe5_SerializeXml
. Press F5 and make sure it compiles without any errors.
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.
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>
button1_Click
event method. 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; } }
System.Xml.Serialization
of the project and then add the using
declaration to the MainPage.xaml.cs
file. 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; }
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; }
SaveXmlToLocalStorage()
and LoadXmlFromLocalStorage()in
the button click event method:private void button1_Click(object sender, RoutedEventArgs e) { SaveXmlToLocalStorage(); LoadXmlFromLocalStorage(); }
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.
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.