コード例 #1
0
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream  Stream = new MemoryStream();
            XmlSerializer xml    = new XmlSerializer(type);

            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                return("");
            }
            Stream.Position = 0;
            StreamReader sr  = new StreamReader(Stream);
            string       str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return(str);
        }
コード例 #2
0
        public static string Save(T item, bool omitXml = false)
        {
            try
            {
                var builder = new StringBuilder();
                using (var stream = XmlWriter.Create(builder,
                                                     new XmlWriterSettings {
                    Indent = true,
                    OmitXmlDeclaration = omitXml
                }))
                {
                    var ser = new XmlSerializer(typeof(T));
                    ser.Serialize(stream, item);
                }

                return(builder.ToString());
            }
            catch (Exception)
            {
            }

            return(string.Empty);
        }