C# Xml字符串与实体Model之间相互转换, 序列化, 反序列化
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApp34
{
class Program
{
static void Main(string[] args)
{
Student student = new Student();
student.Name = "张三";
student.Age = "18";
// 序列化
string xml = XmlSerialize<Student>(student);
/*
<?xml version="1.0"?>
<student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>张三</name>
<age>18</age>
</student>
*/
// 反序列化
Student xml2Model= XmlDeserialize<Student>(xml);
}
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string XmlSerialize<T>(T obj)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
catch
{
throw;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T XmlDeserialize<T>(string xml) where T : class
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch
{
throw;
}
}
}
/// <summary>
/// 学生
/// </summary>
[XmlRoot("student")]
public class Student
{
/// <summary>
/// 姓名
/// </summary>
[XmlElement(ElementName = "name")]
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
[XmlElement(ElementName = "age")]
public string Age { get; set; }
}
}