需要的命名空间:
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
保存XML文件:
private void btWriteXNL_Click(object sender, RoutedEventArgs e)
{
using(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication())
{
using(IsolatedStorageFileStream isoStream=iso.OpenFile("People.xml",FileMode.Create ))
{
XmlWriterSettings xmlsetting = new XmlWriterSettings();
xmlsetting.Indent = true;
using(XmlWriter xmlwriter=XmlWriter.Create(isoStream,xmlsetting))
{
xmlwriter.WriteStartElement("p","person","urn:person");//前缀
xmlwriter.WriteStartElement("FirstName"," ");
xmlwriter.WriteString("Kate");
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("LastName","");
xmlwriter.WriteString("Kitty");
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("Age", "");
xmlwriter.WriteString("20");
xmlwriter.WriteEndElement();
xmlwriter.WriteEndDocument();
xmlwriter.Flush();
}
}
}
}
读取XML文件:
private void btReadXML_Click(object sender, RoutedEventArgs e)
{
try
{
using(IsolatedStorageFile iso=IsolatedStorageFile.GetUserStoreForApplication ())
{
using(IsolatedStorageFileStream isostream=iso.OpenFile ("people.xml",FileMode.Open ))
{
using (StreamReader reader = new StreamReader(isostream))
{
this.textBlock1.Text = reader.ReadToEnd();
}
}
}
}
catch (Exception)
{
throw;
}
}
本文详细介绍了如何使用C#语言结合XML文件进行数据持久化操作,包括XML文件的读写方法、关键步骤解析以及错误处理机制。通过实例演示,帮助开发者掌握在实际项目中灵活运用XML文件进行数据存储与读取的技术。

被折叠的 条评论
为什么被折叠?



