| File was renamed from Utils/XmlUtil.cs |
| | |
| | | using System;
|
| | | using System.IO;
|
| | | using System.Xml.Serialization;
|
| | |
|
| | | namespace WPFProject.Utils
|
| | | {
|
| | | public class XmlUtil
|
| | | {
|
| | | /// <summary>
|
| | | /// 将对象序列化到Xml文件中
|
| | | /// </summary>
|
| | | /// <param name="data">对象</param>
|
| | | /// <param name="filePath">xml路径</param>
|
| | | public static void SerialToFile(object data, string filePath)
|
| | | {
|
| | | XmlSerializer serializer = new XmlSerializer(data.GetType());
|
| | | string content = string.Empty;
|
| | | //serialize
|
| | | using (StringWriter writer = new StringWriter())
|
| | | {
|
| | | serializer.Serialize(writer, data);
|
| | | content = writer.ToString();
|
| | | }
|
| | | //save to file
|
| | | using (StreamWriter stream_writer = new StreamWriter(filePath))
|
| | | {
|
| | | stream_writer.Write(content);
|
| | | }
|
| | | }
|
| | |
|
| | | public static T DeserialFromXml<T>(string filePath)
|
| | | {
|
| | | XmlSerializer serializer = new XmlSerializer(typeof(T));
|
| | | using (StreamReader reader = new StreamReader(filePath))
|
| | | {
|
| | | return (T) serializer.Deserialize(reader);
|
| | | }
|
| | | }
|
| | |
|
| | | }
|
| | | }
|
| | | using System; |
| | | using System.IO; |
| | | using System.Xml.Serialization; |
| | | |
| | | namespace WPFProject.Utils |
| | | { |
| | | public class XmlUtil |
| | | { |
| | | /// <summary> |
| | | /// 将对象序列化到Xml文件中 |
| | | /// </summary> |
| | | /// <param name="data">对象</param> |
| | | /// <param name="filePath">xml路径</param> |
| | | public static void SerialToFile(object data, string filePath) |
| | | { |
| | | XmlSerializer serializer = new XmlSerializer(data.GetType()); |
| | | string content = string.Empty; |
| | | //serialize |
| | | using (StringWriter writer = new StringWriter()) |
| | | { |
| | | serializer.Serialize(writer, data); |
| | | content = writer.ToString(); |
| | | } |
| | | //save to file |
| | | using (StreamWriter stream_writer = new StreamWriter(filePath)) |
| | | { |
| | | stream_writer.Write(content); |
| | | } |
| | | } |
| | | |
| | | public static T DeserialFromXml<T>(string filePath) |
| | | { |
| | | XmlSerializer serializer = new XmlSerializer(typeof(T)); |
| | | using (StreamReader reader = new StreamReader(filePath)) |
| | | { |
| | | return (T) serializer.Deserialize(reader); |
| | | } |
| | | } |
| | | |
| | | } |
| | | } |