我们只要对前一个例子进行简单的修改就可以把我们的App改写成使用SoapFormatter。
1.对System..Runtime.Serialization.Formatters.Soap.dll的引用。(经过我的试验,如果在VS.NET下需要添加,用csc编译不需要)
2.将using语句中的一个using System.Runtime.Serialization.Formatters.Binary改为using System.Runtime.Serialization.Formatters.Soap
3.将所有BinaryFormatter替换为SoapFormatter
4.将生成数据文件扩展名改为.xml
最后的控制台输出与前面例子的一样。
附上修改后的程序:
附上打开VS.NET中打开Insect.XML的截图:
1.对System..Runtime.Serialization.Formatters.Soap.dll的引用。(经过我的试验,如果在VS.NET下需要添加,用csc编译不需要)
2.将using语句中的一个using System.Runtime.Serialization.Formatters.Binary改为using System.Runtime.Serialization.Formatters.Soap
3.将所有BinaryFormatter替换为SoapFormatter
4.将生成数据文件扩展名改为.xml
最后的控制台输出与前面例子的一样。
附上修改后的程序:
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
[Serializable]
public class Insect
{
private string name;
[NonSerialized]
private int id;
public Insect(string name, int id)
{
this.name = name;
this.id= id;
}
public override string ToString()
{
return String.Format("{0}:{1}", name, id);
}
}
class SerializeApp
{
public static void Main(string[] args)
{
Insect i = new Insect("Meadow Brown", 12);
Stream sw = File.Create("Insects.xml");
SoapFormatter bf = new SoapFormatter();
bf.Serialize(sw, i);
sw.Close();
ArrayList box = new ArrayList();
box.Add(new Insect("Marsh Fritillary", 34));
box.Add(new Insect("Speckled Wood", 56));
box.Add(new Insect("Milkweed", 78));
sw = File.Open("Insects.xml", FileMode.Append);
bf.Serialize(sw, box);
sw.Close();
Stream sr = File.OpenRead("Insects.xml");
Insect j = (Insect)bf.Deserialize(sr);
Console.WriteLine(j);
ArrayList bag = (ArrayList)bf.Deserialize(sr);
sr.Close();
foreach(Insect k in bag)
{
Console.WriteLine(k);
}
}
}
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
[Serializable]
public class Insect
{
private string name;
[NonSerialized]
private int id;
public Insect(string name, int id)
{
this.name = name;
this.id= id;
}
public override string ToString()
{
return String.Format("{0}:{1}", name, id);
}
}
class SerializeApp
{
public static void Main(string[] args)
{
Insect i = new Insect("Meadow Brown", 12);
Stream sw = File.Create("Insects.xml");
SoapFormatter bf = new SoapFormatter();
bf.Serialize(sw, i);
sw.Close();
ArrayList box = new ArrayList();
box.Add(new Insect("Marsh Fritillary", 34));
box.Add(new Insect("Speckled Wood", 56));
box.Add(new Insect("Milkweed", 78));
sw = File.Open("Insects.xml", FileMode.Append);
bf.Serialize(sw, box);
sw.Close();
Stream sr = File.OpenRead("Insects.xml");
Insect j = (Insect)bf.Deserialize(sr);
Console.WriteLine(j);
ArrayList bag = (ArrayList)bf.Deserialize(sr);
sr.Close();
foreach(Insect k in bag)
{
Console.WriteLine(k);
}
}
}
附上打开VS.NET中打开Insect.XML的截图: