程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Xml序列化去掉命名空間,去掉申明,xml序列化

Xml序列化去掉命名空間,去掉申明,xml序列化

編輯:C#入門知識

Xml序列化去掉命名空間,去掉申明,xml序列化


#region 序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">類型</param>
        /// <param name="obj">對象</param>
        /// <returns></returns>
        public  string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");//把命名空間設置為空,這樣就沒有命名空間了
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化對象
                xml.Serialize(Stream, obj,ns);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

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

            return str;
        }

        #endregion

 

  public static string ObjectToXmlSerializer(Object Obj)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            //去除xml聲明
            settings.OmitXmlDeclaration = true;
            settings.Encoding = Encoding.Default;
            System.IO.MemoryStream mem = new MemoryStream();
            using (XmlWriter writer = XmlWriter.Create(mem, settings))
            {
                //去除默認命名空間xmlns:xsd和xmlns:xsi
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlSerializer formatter = new XmlSerializer(Obj.GetType());
                formatter.Serialize(writer, Obj, ns);
            }
            return Encoding.Default.GetString(mem.ToArray());
        }
源網址:http://www.cnblogs.com/kissdodog/archive/2013/12/10/3468385.html

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved