【问题标题】:Serialize XML data (Incremental storing) in Windows 8在 Windows 8 中序列化 XML 数据(增量存储)
【发布时间】:2012-06-26 10:40:52
【问题描述】:

如何在 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));
                }
            }
        }
    }

【问题讨论】:

    标签: c# windows windows-8


    【解决方案1】:

    将序列化的 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 8 / RT 的 Windows 存储和异步编写的相同代码的外观:

    /// <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 函数仅用于糖。

    【讨论】:

      【解决方案2】:

      我构建了一个数独应用程序,但我遇到了同样的问题。我尝试在 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);
                          }
                       }                
      
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-01
        • 2010-09-08
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 2016-09-17
        • 2017-10-22
        相关资源
        最近更新 更多