问题
How to serialize XMl data in Windows8.For Metro the methos are asynchronous. For saving an action can be passed that will be called once the save operation is complete. When loading data you'll want to pass an action that will received the loaded data and an exception parameter that will be populated if the data could not be loaded. How is it possible.
Below is the code for serializing in wp7.. how is it poessible in windows 8??
private void SaveProfileData(Profiles profileData)
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
ProfileList = ReadProfileList();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("profile.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Profiles>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, GenerateProfileData(profileData));
}
}
}
}
回答1:
I build a Sudoku app and i have the same problem. I try to Change the code from wp7 to win 8 in visual studio 2012 but my app didn't work yet. Perhaps my code can be help you.
public void SaveToDisk()
{
if (Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
{
if (Windows.Storage.ApplicationData.Current.LocalSettings.Values[key].ToString() != null)
{
//do update
Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
}
}
else
{ // do create key and save value, first time only.
Windows.Storage.ApplicationData.Current.LocalSettings.CreateContainer(key, ApplicationDataCreateDisposition.Always);
if (Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] == null)
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
}
using (StreamWriter writer = new StreamWriter(stream))
{
List<SquareViewModel> s = new List<SquareViewModel>();
foreach (SquareViewModel item in GameArray)
s.Add(item);
XmlSerializer serializer = new XmlSerializer(s.GetType());
serializer.Serialize(writer, s);
}
}
}
回答2:
Writing Serialized XML To File
To serialize to XML on Windows Phone using Isolated Storage:
/// <summary>
/// Saves the given class instance as XML.
/// </summary>
/// <param name="fileName">Name of the xml file to save the data to.</param>
/// <param name="classInstanceToSave">The class instance to save.</param>
public static void SaveToXml(string fileName, T classInstanceToSave)
{
using (IsolatedStorageFile isolatedStorage = GetIsolatedStorageFile)
{
using (IsolatedStorageFileStream stream = isolatedStorage.OpenFile(fileName, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
{
serializer.Serialize(xmlWriter, classInstanceToSave);
}
}
}
}
/// <summary>
/// Gets the Isolated Storage File for the current platform.
/// </summary>
private static IsolatedStorageFile GetIsolatedStorageFile
{
get
{
#if (WINDOWS_PHONE)
return IsolatedStorageFile.GetUserStoreForApplication();
#else
return IsolatedStorageFile.GetUserStoreForDomain();
#endif
}
}
you will also need to have "using System.IO.IsolatedStorage" at the top of your file.
And here is how the same code would look using Windows Storage for Windows 8 / RT and writing asynchronously:
/// <summary>
/// Saves the given class instance as XML asynchronously.
/// </summary>
/// <param name="fileName">Name of the xml file to save the data to.</param>
/// <param name="classInstanceToSave">The class instance to save.</param>
public static async void SaveToXmlAsync(string fileName, T classInstanceToSave)
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
{
serializer.Serialize(xmlWriter, classInstanceToSave);
}
}
}
This requires having "using Windows.Storage" at the top of your file.
Reading Serialized XML From File
To read from serialized XML on Windows Phone using Isolated Storage:
/// <summary>
/// Loads a class instance from an XML file.
/// </summary>
/// <param name="fileName">Name of the file to load the data from.</param>
public static T LoadFromXml(string fileName)
{
try
{
using (IsolatedStorageFile isolatedStorage = GetIsolatedStorageFile)
{
// If the file exists, try and load it it's data.
if (isolatedStorage.FileExists(fileName))
{
using (IsolatedStorageFileStream stream = isolatedStorage.OpenFile(fileName, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T data = (T)serializer.Deserialize(stream);
return data;
}
}
}
}
// Eat any exceptions unless debugging so that users don't see any errors.
catch
{
if (IsDebugging)
throw;
}
// We couldn't load the data, so just return a default instance of the class.
return default(T);
}
/// <summary>
/// Gets if we are debugging the application or not.
/// </summary>
private static bool IsDebugging
{
get
{
#if (DEBUG)
// Extra layer of protection in case we accidentally release a version compiled in Debug mode.
if (System.Diagnostics.Debugger.IsAttached)
return true;
#endif
return false;
}
}
and here is how the same code would look using Windows Storage for Windows 8 / RT and reading asynchronously:
/// <summary>
/// Loads a class instance from an XML file asynchronously.
/// </summary>
/// <param name="fileName">Name of the file to load the data from.</param>
public static async System.Threading.Tasks.Task<T> LoadFromXmlAsync(string fileName)
{
try
{
var files = await System.Threading.Tasks.Task.Run(() => ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName));
var file = files.GetResults().FirstOrDefault(f => f.Name == fileName);
// If the file exists, try and load it it's data.
if (file != null)
{
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T data = (T)serializer.Deserialize(stream);
return data;
}
}
}
// Eat any exceptions unless debugging so that users don't see any errors.
catch
{
if (IsDebugging)
throw;
}
// We couldn't load the data, so just return a default instance of the class.
return default(T);
}
/// <summary>
/// Gets if we are debugging the application or not.
/// </summary>
private static bool IsDebugging
{
get
{
#if (DEBUG)
// Extra layer of protection in case we accidentally release a version compiled in Debug mode.
if (System.Diagnostics.Debugger.IsAttached)
return true;
#endif
return false;
}
}
For me these are helper functions, which is why they are marked as static, but they don't need to be static. Also, the IsDebugging function is there just for sugar.
来源:https://stackoverflow.com/questions/11205565/serialize-xml-data-incremental-storing-in-windows-8