本帖最后由 agameboy 于 2012-5-17 17:08 编辑 这一篇我们会通过XmlSerializer读写XML文件,跟多的相关文章请参考WP7 IsolatedStorage系列篇 ! 需要的命名空间: using System.IO; using System.IO.IsolatedStorage; using System.Xml; using System.Xml.Serialization; 注意你需要在项目中添加System.Xml .Serialization 引用,不然那你就无法实现喽!! 写一个Person类:
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; } } }
复制代码
下面为一个序列化方法:
private List<Person> GeneratePersonData() { List<Person> data = new List<Person>(); data.Add(new Person() { FirstName ="Kate",LastName ="Brown",Age=23}); data.Add(new Person() { FirstName = "Kitty", LastName = "Brown", Age = 22 }); data.Add(new Person() { FirstName = "Mic", LastName = "Brown", Age = 21 }); return data; }
复制代码
保存XML文件:
private void button1_Click(object sender, RoutedEventArgs e) { XmlWriterSettings xmlwriterSettings = new XmlWriterSettings(); xmlwriterSettings.Indent = true;//缩进 using(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication ()) { using(IsolatedStorageFileStream isoStream=iso.OpenFile("People.xml",FileMode.Create)) { XmlSerializer serializer = new XmlSerializer(typeof(List<Person>)); using (XmlWriter xmlWriter = XmlWriter.Create(isoStream, xmlwriterSettings)) { serializer.Serialize(xmlWriter, GeneratePersonData()); } } } }
复制代码
读取XML文件:
private void button2_Click(object sender, RoutedEventArgs e) { using(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication ()) { using(IsolatedStorageFileStream isoStream=iso.OpenFile("People.xml",FileMode.Open)) { XmlSerializer serializer=new XmlSerializer (typeof(List<Person>)); List<Person> data = (List<Person>)serializer.Deserialize(isoStream); listBox1.ItemsSource = data; } } }
复制代码
Binding ListBox:
<ListBox Height="532" HorizontalAlignment="Left" Margin="0,69,0,0" Name="listBox1" VerticalAlignment="Top" Width="450" > <ListBox.ItemTemplate> <DataTemplate > <StackPanel Margin="10" > <TextBlock Height="30" Name="textBlock1" Text="{Binding FirstName}" /> <TextBlock Height="30" Name="textBlock2" Text="{Binding LastName}" /> <TextBlock Height="30" Name="textBlock3" Text="{Binding Age}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
复制代码
提示:当进行文件操作的时候始终使用using 关键字,using 结束后会隐式调用Disposable方法,清理非托管资源。
转载于:https://www.cnblogs.com/Belling/archive/2012/11/29/2794597.html