WP7 isolated storage series-5. Use xmlserializer to read and store XML files

Source: Internet
Author: User

This is the fifth short article "WP7 isolated storage series", focusing on real and practical examples with source code, rather than the theory of inventory. Next I will discuss how to read data from isolated storage and save data to isolated storage.

·
WP7 isolated storage series-1. Isolated Storage
Introduction

·
WP7 isolated storage series-2. Create folders and files

·
WP7 isolated storage series-3. Use isolatedstoragesettings to store data

·
WP7 isolated storage series-4. Read and store text files

·
WP7 isolated storage series-5. Use xmlserializer to read and store XML files

·
WP7 isolated storage series-6. Use xmlwriter to read and store XML files

·
WP7 isolated storage series-7. Reading and storing images

·
WP7 isolated storage series-8. Read and store captured images

·
WP7 isolated storage series-9. Read and store binary files

·
WP7 isolated storage series-10. File Operations

·
WP7 isolated storage series-11. Suggestions and best practices

·
WP7 isolated storage series-12. open source database and help library files

Let's start by creating a simple Windows Phone 7 project. Next, add the following namespaces to mainpage. XAML. CS (or you can use this code on another page ):

using System.Xml;using System.Xml.Serialization;using System.IO.IsolatedStorage;using System.IO;

Note: You will add a reference to system. xml. serialization:

Reading and saving XML files to isolated storage is a very common task in WP7.

Basically, we use the isolatedstoragefilestream class to read, write, and create files in isolated storage. When talking about XML files, the main difference is the use of xmlwriter. We can use xmlserializer to serialize objects to XML documents and deserialize objects from XML documents.

Note: The using declaration is always used for file operations, because it provides a convenient syntax to ensure correct use of the idisposable object.

In this article, we will use the following service class to generate our XML file structure:

public class Person{    string firstname;    string lastname;    int age;    public string FirstName    {        get { return firstname; }        set { firstname = value; }    }    public string LastName    {        get { return lastname; }        set { lastname = value; }    }    public int Age    {        get { return age; }        set { age = value; }    }}

The following describes how to serialize data to XML.

private List<Person> GeneratePersonData(){    List<Person> data = new List<Person>();    data.Add(new Person() { FirstName = "Kate", LastName = "Brown", Age = 25 });    data.Add(new Person() { FirstName = "Tom", LastName = "Stone", Age = 63 });    data.Add(new Person() { FirstName = "Michael", LastName = "Liberty", Age = 37 });    return data;}

Use xmlserializer to save the New XML file to isolated storage

In this example, we will create an XML file named people. XML to isolated storage, and then write data.

// Write to the Isolated StorageXmlWriterSettings xmlWriterSettings = new XmlWriterSettings();xmlWriterSettings.Indent = true;using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()){    using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Create))    {        XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));        using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))        {            serializer.Serialize(xmlWriter, GeneratePersonData());        }    }}

Note: This is the best way to operate XML and isolated storage.

Note: When creating a new file, we use filemode. Create. When we want to write the file, we use fileaccess. Write! You can find information about fileaccess here.

Use xmlserializer to read XML files from isolated storage

In this example, you first open the existing XML file named people. XML from isolated storage and then read its content. The content will be displayed in a ListBox.

try{    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())    {        using(IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open))        {            XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));            List<Person> data = (List<Person>)serializer.Deserialize(stream);            this.listBox.ItemsSource = data;        }    }}catch {    //add some code here}

Note: This is the best way to operate XML and isolated storage.

Note: When you open an existing file from isolated storage, use filemode. Open. When you want to read the file, use fileaccess. Read! You can find information about fileaccess here.

<ListBox x:Name="listBox">    <ListBox.ItemTemplate>        <DataTemplate>            <StackPanel Margin="10" >                <TextBlock Text="{Binding FirstName}"/>                <TextBlock Text="{Binding LastName}"/>                <TextBlock Text="{Binding Age}"/>            </StackPanel>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>

Note: The using declaration is always used for file operations, because it provides a convenient syntax to ensure correct use of the idisposable object.

In this article, I talked about how to use xmlserializer to read and save XML files to isolated storage. Here is all the source code (including all the xmlserializer and xmlwriter examples in the next article ):

 

We look forward to the following articles. I hope this article will help you.

Link: http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-XML-files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.