c# 如何将对象和XML字符串之间进行相互转换呢?


摘要:
下文讲述使用C#代码在对象和xml之间相互转换的方法分享,如下所示;

 
实现思路:
    使用XmlSerializer类即可在对象同xml之间相互转换

例:


//对象转成XML
public static string ObjToXml(object obj)
{
     using (MemoryStream Stream = new MemoryStream()) 
      {
       XmlSerializer xml = new XmlSerializer(obj.GetType());
       xml.Serialize(Stream, obj);
        Stream.Position = 0;
        StreamReader sr = new StreamReader(Stream);
        string str = sr.ReadToEnd();
        return str;
      }
}

//XML字符串转成对象对象
public static T XmlToObj(string xml)
{
    XmlSerializer xserializer = new XmlSerializer(typeof(T));
     using (StringReader sr = new StringReader(xml))
     {
       return (T)xserializer.Deserialize(sr);
     }
}