public class Dog
{
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public string ReturnString()
{
return Id + " " + Name + " " + Sex + " " + Age;
}
}
class Program
{
static void Main(string[] args)
{
List<Dog> list = new List<Dog>()
{
new Dog(){Id=1,Name="旺财",Sex="男",Age=2},
new Dog(){Id=2,Name="哈士奇",Sex="女",Age=4},
new Dog(){Id=3,Name="藏獒",Sex="男",Age=5},
};
//序列化
string xml = XmlSerialize<List<Dog>>(list);
Console.WriteLine("*********** 类--> XML ************");
Console.WriteLine(xml);
//反序列化
string strXML = "<ArrayOfDog><Dog><Id>1</Id><Name>旺财</Name><Sex>男</Sex><Age>2</Age></Dog><Dog><Id>2</Id><Name>哈士奇</Name><Sex>女</Sex><Age>4</Age></Dog><Dog><Id>3</Id><Name>藏獒</Name><Sex>男</Sex><Age>5</Age></Dog></ArrayOfDog>";
List<Dog> listDog = DESerializer<List<Dog>>(strXML);
Console.WriteLine("*********** XML--> 类 ************");
foreach (Dog dog in listDog)
{
Console.WriteLine(dog.ReturnString());
}
Console.ReadKey();
}
/// <summary>
/// 反序列化
/// </summary>
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 序列化
/// </summary>
public static string XmlSerialize<T>(T obj)
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
}
请发表评论