无法使用XML Serializer反序列化多个对象,导致InvalidOperationException

时间:2013-08-27 13:00:08

标签: c# .net xml-serialization xmlserializer xml-deserialization

我有一个简单的类Cust,我想使用XML Serialization进行序列化。

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未处理 - XML文档中的错误(5,10)

我知道如果我将它们放在一个集合中,我可以存储多个对象。

但在这种情况下,我无法将列表附加到xml文件中。我想逐个单独地序列化多个对象;然后我想反序列化它们。

2 个答案:

答案 0 :(得分:0)

使用对象数组

//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, new[]{c1,c2});
fs.Close();

//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

fs.Close();

答案 1 :(得分:0)

诀窍是(以某种方式)将每个 XML 与另一个分开。

  1. 使用 XmlWriter 将对象序列化为文件(紧凑格式,无制表符/新行)
  2. 在文件中添加一个新行(在序列化消息之后)
  3. 重复所有对象
  4. 使用StreamReader.ReadLine逐行读取文件,每一行代表一个完整的XML文档
  5. 为您刚刚读取的每一行创建一个内存流并从中反序列化您的对象