SoFunction
Updated on 2025-03-07

C# Forward and Deserialization XML File Example (xml Serialization)


using ;
using ;
using ;
using ;
using ;
using ;
using ;
using System;

namespace
{
    /// <summary>
/// XML text general interpreter
    /// </summary>
    public class XmlHelper
    {
        private const string EncodePattern = "<[^>]+?encoding=\"(?<enc>[^<>\\s]+)\"[^>]*?>";
        private static readonly Encoding DefEncoding = ("gb2312");
        private static readonly Regex RegRoot = new Regex("<(\\w+?)[ >]", );
        private static readonly Regex RegEncode = new Regex(EncodePattern,
                                                            | );
        private static readonly Dictionary<string, XmlSerializer> Parsers = new Dictionary<string, XmlSerializer>();
#region parser

        static Encoding GetEncoding(string input)
        {
            var match = (input);
            if ()
            {
                try
                {
                    return (("${enc}"));
                }
// ReSharper disable EmptyGeneralCatchClause
                catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
                {
                }
            }
            return DefEncoding;
        }

        /// <summary>
/// parse XML files
        /// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="fileName">File name</param>
/// Instance of <returns> class</returns>
        public T ParseFile<T>(string fileName) where T : class, new()
        {
            var info = new FileInfo(fileName);
            if (!(".xml", ) || !)
            {
throw new ArgumentException("The file name entered is incorrect!");
            }
            string body;
            var tempFileName = ("temp", ().ToString().Replace("-", "") + ".xml");
            var fi = new FileInfo(tempFileName);
            var di = ;
            if (di != null && !)
            {
                ();
            }
            (fileName, tempFileName);
            using (Stream stream = (tempFileName, , ))
            {
                using (TextReader reader = new StreamReader(stream, DefEncoding))
                {
                    body = ();
                }
            }
            (tempFileName);
            var enc = GetEncoding(body);
            if (!Equals(enc, DefEncoding))
            {
                var data = (body);
                var dest = (DefEncoding, enc, data);
                body = (dest);
            }
            return Parse<T>(body, enc);
        }

        /// <summary>
/// Serialize the object into an XML file
        /// </summary>
/// <param name="fileName">File name</param>
/// <param name="obj">Object</param>
        /// <returns></returns>
/// <exception cref="ArgumentException">File name error exception</exception>
        public bool SaveFile(string fileName, object obj)
        {
            return SaveFile(fileName, obj, DefEncoding);
        }

        /// <summary>
/// Serialize the object into an XML file
        /// </summary>
/// <param name="fileName">File name</param>
/// <param name="obj">Object</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
/// <exception cref="ArgumentException">File name error exception</exception>
        public bool SaveFile(string fileName, object obj,Encoding encoding)
        {
            var info = new FileInfo(fileName);
            if (!(".xml", ))
            {
throw new ArgumentException("The file name entered is incorrect!");
            }
            if (obj == null) return false;
            var type = ();
            var serializer = GetSerializer(type);

            using (Stream stream = (fileName, , ))
            {
                using (TextWriter writer = new StreamWriter(stream, encoding))
                {
                    (writer, obj);
                }
            }
            return true;
        }
        static XmlSerializer GetSerializer(Type type)
        {
            var key = ;
            XmlSerializer serializer;
            var incl = (key, out serializer);
            if (!incl || serializer == null)
            {
                var rootAttrs = new XmlAttributes { XmlRoot = new XmlRootAttribute() };
                var attrOvrs = new XmlAttributeOverrides();
                (type, rootAttrs);
                try
                {
                    serializer = new XmlSerializer(type, attrOvrs);
                }
                catch (Exception e)
                {
throw new Exception("Type declaration error!" + e);
                }
                Parsers[key] = serializer;
            }
            return serializer;
        }
        /// <summary>
/// parse text
        /// </summary>
/// <typeparam name="T">Class that need to be parsed</typeparam>
/// <param name="body">text to be parsed</param>
/// Instance of <returns> class</returns>
        public T Parse<T>(string body) where T : class, new()
        {
            var encoding = GetEncoding(body);
            return Parse<T>(body, encoding);
        }

        /// <summary>
/// parse text
        /// </summary>
/// <typeparam name="T">Class that need to be parsed</typeparam>
/// <param name="body">text to be parsed</param>
        /// <param name="encoding"></param>
/// Instance of <returns> class</returns>
        public T Parse<T>(string body, Encoding encoding) where T : class, new()
        {
            var type = typeof (T);
            var rootTagName = GetRootElement(body);

            var key = ;
            if (!(rootTagName))
            {
throw new ArgumentException("The input text is incorrect! key:" + key + "\t\troot:" + rootTagName);
            }

            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream((body)))
            {
                obj = (stream);
            }
            if (obj == null) return null;
            try
            {
                var rsp = (T) obj;
                return rsp;
            }
            catch (InvalidCastException)
            {
                var rsp = new T();
                var pisr = typeof (T).GetProperties();
                var piso = ().GetProperties();
                foreach (var info in pisr)
                {
                    var info1 = info;
                    foreach (var value in from propertyInfo in piso where () select (obj, null))
                    {
                        (rsp, value, null);
                        break;
                    }
                }
                return rsp;
            }
        }

        private static XmlSerializer BuildSerializer(Type type)
        {
            var rootAttrs = new XmlAttributes { XmlRoot = new XmlRootAttribute() };
            var attrOvrs = new XmlAttributeOverrides();
            (type, rootAttrs);
            try
            {
                return new XmlSerializer(type, attrOvrs);
            }
            catch (Exception e)
            {
throw new Exception("Type declaration error!" + e);
            }
        }

        /// <summary>
/// parse unknown type of XML content
        /// </summary>
/// <param name="body">Xml text</param>
/// <param name="encoding">character encoding</param>
        /// <returns></returns>
        public object ParseUnknown(string body, Encoding encoding)
        {
            var rootTagName = GetRootElement(body);
            var array = ();
            Type type = null;
            foreach (var assembly in array)
            {
                type = (rootTagName, false, true);
                if (type != null) break;
            }
            if (type == null)
            {
().Warn("Loading {0} XML type failed! ", rootTagName);
                return null;
            }
            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream((body)))
            {
                obj = (stream);
            }

            var rsp = obj;
            return rsp;
        }
        /// <summary>
/// Serialize objects in XML
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serialize(object obj)
        {
            if (obj == null) return ;
            var type = ();
            var serializer = GetSerializer(type);
            var builder = new StringBuilder();
            using (TextWriter writer = new StringWriter(builder))
            {
                (writer, obj);
            }
            return ();
        }
        #endregion

        /// <summary>
/// Get the root node name of the XML response
        /// </summary>
        private static string GetRootElement(string body)
        {
            var match = (body);
            if ()
            {
                return [1].ToString();
            }
            throw new Exception("Invalid XML format!");
        }

    }
}