我有一个简单的类 Cust,我想使用 XML 序列化对其进行序列化。
public class Cust
{
public string CustName;
public int ID;
public Cust() { }
public Cust(string nm, int id)
{
CustName = nm;
ID = id;
}
public string DisInfo()
{
return CustName+" "+ID;
}
}
我的序列化功能是:
private void button1_Click(object sender, EventArgs e)
{
//Serialize
FileStream fs = new FileStream(@"C:\tmp\cust.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(Cust));
Cust c1 = new Cust("Rahul S",111);
Cust c2 = new Cust("John D", 222);
xs.Serialize(fs, c1);
xs.Serialize(fs, c2);
fs.Close();
}
输出是 cust.xml
<?xml version="1.0"?>
<Cust xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustName>Rahul S</CustName>
<ID>111</ID>
</Cust><?xml version="1.0"?>
<Cust xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustName>John D</CustName>
<ID>222</ID>
</Cust>
然后我尝试反序列化;从 xml 文件中取回 Cust 对象
private void button2_Click(object sender, EventArgs e)
{
//Deserialize
FileStream fs = new FileStream(@"C:\tmp\cust.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlSerializer xs = new XmlSerializer(typeof(Cust));
Cust c1 = (Cust)xs.Deserialize(fs);//Exception
Cust c2 = (Cust)xs.Deserialize(fs);
fs.Close();
}
这会引发异常
InvalidOperationException Unhandled- XML 文档中的错误 (5,10)
我知道如果我将它们放在一个集合中,我可以存储多个对象。
但在那种情况下,我将无法将列表附加到 xml 文件中。我想逐个序列化多个对象;然后我想反序列化它们。