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());
       }

    }

猜你喜欢

转载自www.cnblogs.com/zhengwei-cq/p/9052340.html