我用的对象实体 泛型的使用率比较高,不过泛型序化反序化出错请高手赐教。
对象实体
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace xmlXuLieHua
{
/// <summary>
/// xml 序列化与反序列化
/// chenxun 2009年3月18日10:35:53 对象
/// </summary>
[Serializable, XmlRoot(Namespace = "http://yunge.com")]
public class Students
{
private IList <Student> _Student;
[System.Xml.Serialization.XmlElementAttribute("Student")]
public IList <Student> Student
{
set { _Student = value; }
get { return _Student; }
}
}
[Serializable, XmlRoot(Namespace = "http://yunge.com")]
public class Student
{
private long _Number;
private string _Name;
private bool _enabled;
public IList <Dorm> _dorm;
public long Number
{
set { _Number = value; }
get { return _Number; }
}
public string Name
{
set { _Name = value; }
get { return _Name; }
}
public bool Enabled
{
set { _enabled=value;}
get{return _enabled;}
}
[System.Xml.Serialization.XmlElementAttribute("dorm")]
public IList <Dorm> Dorm
{
set { _dorm = value; }
get { return _dorm; }
}
}
[Serializable, XmlRoot(Namespace = "http://yunge.com")]
public class Dorm
{
private string _Name;
private string _Number;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Number
{
get { return _Number; }
set { _Number = value; }
}
}
}
xml 格式
<?xml version="1.0"?>
<Students xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://yunge.com">
<Student>
<Number>222222 </Number>
<Name>2222 </Name>
<enabled>true </enabled>
<dorm>
<Name>222 </Name>
<Number>22-22-2 </Number>
</dorm>
<dorm>
<Name>222 </Name>
<Number>22-222-2 </Number>
</dorm>
</Student>
<Student>
<Number>333333 </Number>
<Name>3333333333 </Name>
<enabled>false </enabled>
<dorm>
<Name>333333 </Name>
<Number>33-333-3 </Number>
</dorm>
<dorm>
<Name>3333 </Name>
<Number>33-3333-333 </Number>
</dorm>
</Student>
</Students>
使用 List而不是IList看看。
序列化属性改成最简单的[Serializable()]试试,或者你尝试一下不用XML做序列化,用二进制做序列化操作。给你一个序列和反序列的泛型例子。
public static string Serialize<T>(T t)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, t);
byte[] bytes = ms.ToArray();
return System.Text.Encoding.UTF8.GetString(bytes);
}
public static T Deserialize<T>(Type type, string s)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(bytes);
BinaryFormatter formatter = new BinaryFormatter();
T t = (T)formatter.Deserialize(ms);
return t;
}