X3

RedSky

导航

Xml序列化和反序列化

 

public class XMLHelper
{
    public static string Serialize<T>(T entity, Encoding encoding = null)
    {
        StringBuilder sb = new StringBuilder();
        XmlSerializer serializer = new XmlSerializer(typeof(T), GetTypes(obj));

        if (encoding == null)
        {
            using (TextWriter tw = new StringWriter(sb))
                serializer.Serialize(tw, entity);
            return sb.ToString();
        }

        using (MemoryStream ms = new MemoryStream())
            using (StreamWriter sw = new StreamWriter(ms, encoding))
        {
            serializer.Serialize(sw, entity);
            byte[] bytes = ms.ToArray();
            return encoding.GetString(bytes, 0, bytes.Length);
        }
    }

    public static void AppendSerializeNameSpace(XmlDocument doc)
    {
        if (string.IsNullOrWhiteSpace(doc.InnerText)) return;
        if (!doc.DocumentElement.HasAttribute("xmlns:xsi"))
            doc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        if (!doc.DocumentElement.HasAttribute("xmlns:xsd"))
            doc.DocumentElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    }

    public static void SerializeToFile<T>(string filePath, T obj, string rootName = null)
    {
        using (StreamWriter sw = new StreamWriter(filePath))
        {
            XmlSerializer serializer = string.IsNullOrWhiteSpace(rootName) ?
                new XmlSerializer(typeof(T), GetTypes(obj))
                : new XmlSerializer(typeof(T), null, GetTypes(obj), new XmlRootAttribute(rootName), null);
            serializer.Serialize(sw, obj);
        }
    }

    public static T DeserializeFromFile<T>(string filePath)
    {
        using (StreamReader sr = new StreamReader(filePath))
        {
            var setting = new XmlReaderSettings
            {
                CheckCharacters = false//保留等于空格的字符串值,默认会忽略空格而赋值为null,比如<demo> </demo>,解析默认会demo=null,CheckCharacters=false时demo=" "
            };
            using (XmlReader r = XmlReader.Create(sr, setting))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(r);
            }
        }
    }

    public static T Deserialize<T>(string xmlString)
    {
        T cloneObject = default(T);

        StringBuilder buffer = new StringBuilder();
        buffer.Append(xmlString);

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (TextReader reader = new StringReader(buffer.ToString()))
        {
            Object obj = serializer.Deserialize(reader);
            cloneObject = (T)obj;
        }

        return cloneObject;
    }
    
    /// <summary>
    /// 派生类序列化
    ///</summary>
    public static Type[] GetTypes(object o)
    {
        Type type = o.GetType();
        HashSet<Type> types= new HashSet<Type> { o.GetType() };
        var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
        foreach (var item in properties)
        {
            if(item.PropertyType.IsClass && item.PropertyType != typeof(string))
            {
                object v = item.GetValue(o);
                if (v == null) continue;
                var ins = item.PropertyType.GetInterfaces();
                if (ins != null && ins.Contains(typeof(IEnumerable)))
                {
                    IEnumerator enumerator = (v as IEnumerable)?.GetEnumerator();
                    if (enumerator != null)
                        while (enumerator.MoveNext())
                        {
                            var ts = GetTypes(enumerator.Current);
                            if (ts != null)
                                foreach (var t in ts)
                                    types.Add(t);
                        }
                }
                else
                {
                    var ts = GetTypes(v);
                    if (ts != null)
                        foreach (var t in ts)
                            types.Add(t);
                }
            }
        }
        return types.ToArray();
    }
}

 

posted on 2022-04-07 15:49  HotSky  阅读(33)  评论(0编辑  收藏  举报