1

我有一个简单的类 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 文件中。我想逐个序列化多个对象;然后我想反序列化它们。

4

2 回答 2

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();
于 2013-08-27T13:05:53.087 回答
0

诀窍是(以某种方式)将每个 XML 彼此分开。

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