将对象序列化
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// 将对象转换为 XML 字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToXmlString(Model.Student obj)
{
using (MemoryStream ms = new MemoryStream())
{
System.Type type = obj.GetType();
XmlSerializer serializer = new XmlSerializer(type);
try
{
serializer.Serialize(ms, obj);
ms.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return string.Empty;
}
}
}
/// <summary>
/// 将对象转换为 XML 文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static void ToXmlFile(Model.Student obj)
{
using (FileStream fs = new FileStream(@"D:\xsdj.xml", FileMode.Create))
{
System.Type type = obj.GetType();
XmlSerializer serializer = new XmlSerializer(type);
try
{
serializer.Serialize(fs, obj);
fs.Close();
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
}
}
/// 将对象转换为 XML 字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToXmlString(Model.Student obj)
{
using (MemoryStream ms = new MemoryStream())
{
System.Type type = obj.GetType();
XmlSerializer serializer = new XmlSerializer(type);
try
{
serializer.Serialize(ms, obj);
ms.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
return string.Empty;
}
}
}
/// <summary>
/// 将对象转换为 XML 文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static void ToXmlFile(Model.Student obj)
{
using (FileStream fs = new FileStream(@"D:\xsdj.xml", FileMode.Create))
{
System.Type type = obj.GetType();
XmlSerializer serializer = new XmlSerializer(type);
try
{
serializer.Serialize(fs, obj);
fs.Close();
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
}
}