[WPF]xml序列化以及反序列化数据
生活随笔
收集整理的這篇文章主要介紹了
[WPF]xml序列化以及反序列化数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
?
XML序列化工具類?
public static class XMLHelper{/// <summary>/// 將對象序列化為指定的文件名/// </summary>/// <typeparam name="T"></typeparam>/// <param name="obj"></param>/// <param name="fileName"></param>/// <returns></returns>public static bool SaveObjAsXml<T>(T obj,string fileName){var dir = Application.StartupPath;try{FileStream fs = new FileStream(dir+"/"+fileName, FileMode.Create);XmlSerializer xs = new XmlSerializer(typeof(T));xs.Serialize(fs, obj);fs.Close();return true;}catch (Exception e){Console.WriteLine(e);throw;}}/// <summary>/// 將xml文件進行反序列化/// </summary>/// <typeparam name="T"></typeparam>/// <param name="fileName"></param>/// <returns></returns>public static T DecodeXML<T>(string fileName){var dir = Application.StartupPath;fileName = dir + "/" + fileName;try{if (File.Exists(fileName)==false)return default(T);FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);XmlSerializer xs = new XmlSerializer(typeof(T));T obj = (T)xs.Deserialize(fs);return obj;}catch(Exception ex){Console.WriteLine(ex.Message);throw;}}}?對應的窗體數據類可以定義為:
[XmlRoot]public class WindowsData:PropertyChangedBase{[XmlElement("WindowsIndex")]/// <summary>/// Windows窗體索引/// </summary>public int WindowsIndex{get;set; }[XmlElement("FontSize")]private double fontSize=14;/// <summary>/// 窗體字體/// </summary>public double FontSize{get { return fontSize;}set{fontSize=value;OnPropertyChanged("FontSize");}}private Point startUpPosition;[XmlElement("LeftTopWinPosition")]public Point StartUpPosition{get { return startUpPosition; }set{startUpPosition = value;OnPropertyChanged("StartUpPosition");}}/// <summary>/// 窗體寬度/// </summary>private int windowsWidth;public int WindowsWidth{get { return windowsWidth; }set { windowsWidth = value;OnPropertyChanged("WindowsWidth"); }}private int windowsHeight;public int WindowsHeight{get { return windowsHeight; }set{windowsHeight = value;OnPropertyChanged("WindowsHeight");}}private string richTextBoxContent;[XmlElement("UserInputNotes")]public string RichTextBoxContent{get { return richTextBoxContent; }set{richTextBoxContent = value;OnPropertyChanged("RichTextBoxContent");}}public WindowsData(){ // MessageBox.Show("新的窗體數據加載了");WindowsIndex = GenerateWindowsIndex.Generate();WindowsWidth = 350;WindowsHeight = 450;double screenHeight = SystemParameters.FullPrimaryScreenHeight;double screenWidth = SystemParameters.FullPrimaryScreenWidth;StartUpPosition =new Point((screenWidth - WindowsWidth)/2,(screenHeight - WindowsHeight)/2);}}?
轉載于:https://www.cnblogs.com/lizhenghao126/p/11053590.html
總結
以上是生活随笔為你收集整理的[WPF]xml序列化以及反序列化数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS-笔记 字符编码
- 下一篇: 超越kmeans:聚类算法概述