| | |
| | | using System; |
| | | using System.CodeDom; |
| | | using System.Collections.Generic; |
| | | using System.IO; |
| | | using System.Reflection; |
| | | using System.Text; |
| | | using System.Web.UI.WebControls; |
| | | using System.Xml; |
| | | using System.Xml.Serialization; |
| | | using static System.Net.WebRequestMethods; |
| | |
| | | { |
| | | public static class XmlHelper |
| | | { |
| | | |
| | | static readonly XmlSerializerNamespaces DEFAULT_NS = new XmlSerializerNamespaces(); |
| | | |
| | | static XmlHelper() |
| | | { |
| | | DEFAULT_NS.Add("", ""); |
| | | } |
| | | |
| | | /// <summary> |
| | | /// serialize object to xml file. |
| | | /// </summary> |
| | |
| | | //serialize |
| | | using (StringWriter writer = new StringWriter()) |
| | | { |
| | | serializer.Serialize(writer, obj); |
| | | serializer.Serialize(writer, obj, DEFAULT_NS); |
| | | content = writer.ToString(); |
| | | } |
| | | //save to file |
| | |
| | | return (T)serializer.Deserialize(reader); |
| | | } |
| | | } |
| | | public static bool ReadFromXml<T>(T obj, string path) { |
| | | public static bool ReadFromXml<T>(T obj, string path) |
| | | { |
| | | XmlDocument xd = new XmlDocument(); |
| | | xd.Load(path); |
| | | |
| | | Type type = typeof(T); |
| | | XmlNode root = xd.SelectSingleNode(type.Name); |
| | | if (root == null) { |
| | | if (root == null) |
| | | { |
| | | return false; |
| | | } |
| | | |
| | |
| | | return true; |
| | | } |
| | | |
| | | public static T DeepClone<T>(T data) |
| | | { |
| | | using (MemoryStream stream = new MemoryStream()) |
| | | { |
| | | XmlSerializer serializer = new XmlSerializer(typeof(T)); |
| | | serializer.Serialize(stream, data); |
| | | stream.Seek(0, SeekOrigin.Begin); |
| | | return (T)serializer.Deserialize(stream); |
| | | } |
| | | } |
| | | } |
| | | } |