Exemplo n.º 1
0
        /// <summary>
        /// Deserialize string to object.
        /// </summary>
        /// <typeparam name="T">
        /// Typeparam.
        /// </typeparam>
        /// <param name="xml">
        /// XML string.
        /// </param>
        /// <returns>
        /// Returns object.
        /// </returns>
        public static T XmlStr2Obj <T>(string xml)
        {
            if (xml == null)
            {
                return(default(T));
            }

            if (string.IsNullOrEmpty(xml))
            {
                return((T)Activator.CreateInstance(typeof(T)));
            }

            StringReader  reader = new StringReader(xml);
            XmlSerializer sr     = SerializerCache.GetSerializer(typeof(T));

            return((T)sr.Deserialize(reader));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Serialize object to string.
        /// </summary>
        /// <param name="obj">
        /// Object.
        /// </param>
        /// <returns>
        /// Returns string.
        /// </returns>
        public static string Obj2XmlStr(object obj)
        {
            if (obj == null)
            {
                return(string.Empty);
            }

            XmlSerializer sr = SerializerCache.GetSerializer(obj.GetType());

            StringBuilder sb = new StringBuilder();
            StringWriter  w  = new StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture);

            // ReSharper disable RedundantExplicitArrayCreation
            sr.Serialize(
                w,
                obj,
                new XmlSerializerNamespaces(new XmlQualifiedName[] { new XmlQualifiedName(string.Empty) }));
            // ReSharper restore RedundantExplicitArrayCreation

            return(sb.ToString());
        }