在.net中使用XmlSerializer类进行序列化与反序列化操作是非常方便的,见下面的代码:
[Serializable]
public class UserInfo
{
/// <summary>
/// 人名称
/// </summary>
public string Name
{
get;
set;
}
public DateTime Date
{
get;
set;
}
public double Age
{
get;
set;
}
public string Remark
{
get;
set;
}
}
[Serializable]
public class SerializerList : ICollection
{
private ArrayList list = new ArrayList();
public SerializerList()
{ }
public UserInfo this[int index]
{
get
{
return (UserInfo)this.list[index];
}
set
{
this.list[index] = value;
}
}
public int Add(UserInfo iap)
{
return this.list.Add(iap);
}
public void Remove(UserInfo iap)
{
this.list.Remove(iap);
}
public void RemoveAt(int index)
{
this.list.RemoveAt(index);
}
public int Count
{
get
{
return this.list.Count;
}
}
#region ICollection 成员
void ICollection.CopyTo(Array array, int index)
{
this.list.CopyTo(array, index);
}
int ICollection.Count
{
get { return this.list.Count; }
}
bool ICollection.IsSynchronized
{
get { return this.list.IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return this.list.SyncRoot; }
}
#endregion
#region IEnumerable 成员
IEnumerator IEnumerable.GetEnumerator()
{
return this.list.GetEnumerator();
}
#endregion
}
SerializerList list = new SerializerList();
public bool SerializeObjecy(string path)
{
XmlSerializer xml = new XmlSerializer(typeof(SerializerList));
StreamWriter sw = new StreamWriter(path, false, Encoding.Default);
try
{
xml.Serialize(sw, this.list);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
finally
{
if (sw != null)
{
sw.Close();
}
}
return true;
}
public bool DeserializeObject(string path)
{
XmlSerializer xml = new XmlSerializer(typeof(SerializerList));
XmlReader sr = new XmlTextReader(path);
try
{
this.list = (SerializerList)xml.Deserialize(sr);
}
catch (Exception e)
{
return false;
}
finally
{
if (sr != null)
{
sr.Close();
}
}
return true;
}
序列化一个对象,会生成一个xml文件;同样,这个xml文件也可以被反序列化。
生成的xml文件的格式为
<?xml version="1.0" encoding="utf-8"?>
<SerializerList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserInfo>
<Name>dddd</Name>
<Date>2010-04-02T10:31:47.8562957+08:00</Date>
<Age>11</Age>
<Remark>dddddd</Remark>
</UserInfo>
</SerializerList>
一般情况下,序列化不会产生什么问题,问题最多的出现在反序列化上,最常见的就是:
XML反序列化出错,XML 文档(2, 2)中有错误,不应有<SerializerList xmlns=''>
这个错误的原因是反序列化时,xml文件与类不一致。解决的方法就是将对象序列化,打开xml文件看看。