xml和对象 转换

时间:2022-08-17 05:17:38
//测试数据
static List<User> list = new List<User>()
{
new User(){id=1001 ,name="语文",buyer="A"},
new User(){id=1001 ,name="语文",buyer="A"},
new User(){id=1001 ,name="数学",buyer="A"},
new User(){id=1001 ,name="数学",buyer="B"},
new User(){id=1001 ,name="数学",buyer="B"},
new User(){id=1002 ,name="英语",buyer="C"},
new User(){id=1005 ,name="英语",buyer="A"},
new User(){id=1005 ,name="英语",buyer="A"},
new User(){id=1005 ,name="英语",buyer="B"},
new User(){id=1004 ,name="计算机",buyer="A"},
new User(){id=1007 ,name="计算机",buyer="C"},
};
//实体模型
public class User
{
public int id { get; set; }
public virtual string name { get; set; }
public virtual string buyer { get; set; }
public virtual string idArr { get; set; }
public virtual DateTime expiredTime { get; set; }
} static void Main(string[] args)
{
//测试数据 xml
string xml = XMLSerialize<List<User>>(list); //xml 转 对象
List<User> ulist = XmlDeserialize<List<User>>(xml);
//输出查看结果
ulist.ForEach(x => Console.WriteLine(x.name)); Console.ReadLine();
} //序列化xml
public static string XMLSerialize<T>(T entity)
{
StringBuilder buffer = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer))
{
serializer.Serialize(writer, entity);
} return buffer.ToString(); } //反序列化xml
public static T XmlDeserialize<T>(string xmlString)
{
T myObject;
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringReader reader = new StringReader(xmlString);
myObject = (T)serializer.Deserialize(reader);
reader.Close();
return myObject;
}