XmlHelper

public static class XmlHelper
    {
       /// <summary>
       /// 将对象序列化成xml
       /// </summary>
       /// <param name="Obj">对象</param>
       /// <param name="ObjType">类名</param>
       /// <returns></returns>
       public static string ToXml(object Obj, Type ObjType)
       {
           XmlSerializer serializer = new XmlSerializer(ObjType);
           string str = string.Empty;
           using (MemoryStream stream = new MemoryStream())
           {
               using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
               {
                   serializer.Serialize((XmlTextWriter)writer,Obj);
               }
               str = Encoding.UTF8.GetString(stream.GetBuffer());
               str = str.Substring(str.IndexOf(Convert.ToChar(60)));
               return str.Substring(0,str.LastIndexOf(Convert.ToChar(0x3e))+1);
           }
       }
       public static string ToXml(object obj)
       {
           return ToXml(obj, true);
       }

       public static string ToXml(object Obj, bool wellFormatted)
       {
           XmlSerializer serializer = new XmlSerializer(Obj.GetType());
           string str = null;
           using (MemoryStream stream = new MemoryStream())
           {
               using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
               {
                   if (wellFormatted)
                   {
                       writer.Formatting = Formatting.Indented;
                       writer.Indentation = 4;
                   }
                   serializer.Serialize((XmlWriter)writer, Obj);
               }
               str = Encoding.UTF8.GetString(stream.GetBuffer());
               str = str.Substring(str.IndexOf(Convert.ToChar(60)));
               return str.Substring(0, str.LastIndexOf(Convert.ToChar(0x3e)) + 1);
           }
       }
       public static void ToXml(object obj, Type objType, Stream stream)
       {
           StreamWriter writer = new StreamWriter(stream);
           try
           {
               new XmlSerializer(objType).Serialize((TextWriter)writer, obj);
           }
           finally
           {
               writer.Flush();
           }
       }
       public static void ToXmlFile(object Obj, string fileName)
       {
           string contents = ToXml(Obj);
           File.WriteAllText(fileName, contents, new UTF8Encoding());
       }
       public static void ToXmlFile(object Obj, Type ObjType, string fileName)
       {
           string contents = ToXml(Obj, ObjType);
           File.WriteAllText(fileName, contents, new UTF8Encoding());
       }
       public static void ToXmlFile(object Obj, Type ObjType, string fileName)
       {
           string contents = ToXml(Obj, ObjType);
           File.WriteAllText(fileName, contents, new UTF8Encoding());
       }

    }

 

posted @ 2018-05-17 17:52  爱生活,爱代码  阅读(115)  评论(0编辑  收藏  举报