Windows 8.1 序列化与反序列化

  /// <summary>
/// 对象序列化成 XML String
/// </summary>
public static void XmlSerialize<T>(T obj, string fieldTickefolderName, string fieldTicketName)
{
string xmlString = string.Empty;
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
xmlSerializer.Serialize(ms, obj);
xmlString = Encoding.UTF8.GetString(ms.ToArray(), , ms.ToArray().Length);
}
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
IAsyncOperation<StorageFolder> storageFolder =
ApplicationData.Current.LocalFolder.CreateFolderAsync(fieldTickefolderName, CreationCollisionOption.ReplaceExisting);
IAsyncOperation<StorageFile> xmlStorageFile =
ApplicationData.Current.LocalFolder.CreateFileAsync(fieldTickefolderName+"\\"+fieldTicketName, CreationCollisionOption.ReplaceExisting);
xmlDocument.SaveToFileAsync(xmlStorageFile.GetResults()); }
  ///// <summary>
///// XML String 反序列化成对象
///// </summary>
public static async Task<T> XmlDeserialize<T>(string fieldTickefolderName, string fieldTicketName)
{
try
{
StorageFolder storageFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(fieldTickefolderName);
StorageFile xmlStorageFile = await storageFolder.GetFileAsync(fieldTicketName); var stream = await xmlStorageFile.OpenAsync(FileAccessMode.Read);
XmlLoadSettings xmlloadsettings = new XmlLoadSettings();
xmlloadsettings.ProhibitDtd = false;
xmlloadsettings.ResolveExternals = false;
XmlDocument doc = await XmlDocument.LoadFromFileAsync(xmlStorageFile, xmlloadsettings);
string xmlString = doc.GetXml();
T t = default(T);
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
using (XmlReader xmlReader = XmlReader.Create(xmlStream))
{
Object obj = xmlSerializer.Deserialize(xmlReader);
t = (T)obj;
}
}
return t; }
catch (Exception ex)
{ throw new Exception(ex.Message);
} }
上一篇:09_Java8操作集合的一些新特性


下一篇:sql错误代码一览表