代码如下:
using
System;
using System.IO;
using System.Xml.Serialization;
// [Serializable]
public class Insect
{
public string name;
//[NonSerialized]
[XmlIgnore]public 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);
}
public Insect() {}
}
class SerializeRawXMLApp
{
[STAThread]
static void Main(string[] args)
{
Insect i = new Insect("Meadow Brown", 12);
XmlSerializer x = new XmlSerializer(typeof(Insect));
Stream s = File.Create("AnInsect.xml");
x.Serialize(s, i);
s.Seek(0, SeekOrigin.Begin);
Insect j = (Insect)x.Deserialize(s);
s.Close();
Console.WriteLine(j);
}
}
using System.IO;
using System.Xml.Serialization;
// [Serializable]
public class Insect
{
public string name;
//[NonSerialized]
[XmlIgnore]public 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);
}
public Insect() {}
}
class SerializeRawXMLApp
{
[STAThread]
static void Main(string[] args)
{
Insect i = new Insect("Meadow Brown", 12);
XmlSerializer x = new XmlSerializer(typeof(Insect));
Stream s = File.Create("AnInsect.xml");
x.Serialize(s, i);
s.Seek(0, SeekOrigin.Begin);
Insect j = (Insect)x.Deserialize(s);
s.Close();
Console.WriteLine(j);
}
}
注意:
1.这里去掉了Serializable属性和NonSerilizable属性,使用XMLIgnore属性完成NonSerialized类似的功能。
2.XmlSerializer不能安全的访地问私有成员,所以我们改为共有成员,也可以提供合适的公有属性(Property)。
3.Xml要求我们的类有一个默认构造器,这个条件可能已经满足了。
我们可以用VS.NET打开AnInsect.xml文件,可以看到以下信息:
<?xml version="1.0"?>
<Insect xmlns:xsd=" http://www.w3.org/2001/XMLSchema" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance">
<name>Meadow Brown</name>
</Insect>