簡體   English   中英

在Windows 8中序列化XML數據(增量存儲)

[英]Serialize XML data (Incremental storing) in Windows 8

如何在Windows8中序列化XMl數據。對於Metro,這些方法是異步的。 對於保存,可以傳遞一旦保存操作完成后將調用的操作。 加載數據時,您需要傳遞將接收加載數據的操作,以及在無法加載數據時將填充的異常參數。 這怎么可能。

下面是在wp7中序列化的代碼..在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));
                }
            }
        }
    }

將序列化XML寫入文件

要使用獨立存儲在Windows Phone上序列化為XML:

/// <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
    }
}

您還需要在文件頂部“使用System.IO.IsolatedStorage”。

以下是使用Windows Storage for Windows 8 / RT和異步寫入的相同代碼的外觀:

/// <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);
        }
    }
}

這需要在文件頂部“使用Windows.Storage”。


從文件中讀取序列化XML

使用獨立存儲從Windows Phone上的序列化XML讀取:

/// <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;
    }
}

以下是使用Windows Storage for Windows 8 / RT和異步讀取的相同代碼的外觀:

/// <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;
    }
}

對我來說,這些是輔助函數,這就是為什么它們被標記為靜態,但它們不需要是靜態的。 此外,IsDebugging功能只適用於糖。

我構建了一個Sudoku應用程序,我遇到了同樣的問題。 我嘗試在Visual Studio 2012中將代碼從wp7更改為win 8,但我的應用程序尚未運行。 也許我的代碼可以幫到你。

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);
                    }
                 }                

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM