XML 序列化仅将对象的公共字段和属性值序列化为 XML 流.
要序列化的对象如下:
public class A
{
private string _ConnectionString;
public string ConnectionString
{
get{return _ConnectionString;}
set{_ConnectionString = value;}
}
private string _AppPath;
public string AppPath
{
get{return _AppPath;}
set{_AppPath = value;}
}
private int _PowerID;
public int PowerID
{
get{return _PowerID;}
set{_PowerID = value;}
}
}
序列化操作:
private void button1_Click(object sender, System.EventArgs e)
{
A a = new A();
a.AppPath = "aaa";
a.ConnectionString = "bbb";
a.PowerID = 99;
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new XmlSerializer(typeof(A));
// To write to a file, create a StreamWriter object.
StringWriter tw = new StringWriter();
mySerializer.Serialize(tw, a);
wl(tw.ToString());
}
结果:
<?xml version="1.0" encoding="utf-16"?>
<A xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ConnectionString>bbb</ConnectionString>
<AppPath>aaa</AppPath>
<PowerID>99</PowerID>
</A>
反序列化操作:
private void button2_Click(object sender, System.EventArgs e)
{
A a ;
// Constructs an instance of the XmlSerializer with the type
// of object that is being deserialized.
XmlSerializer mySerializer = new XmlSerializer(typeof(A));
// To read the file, creates a FileStream.
StringReader sr = new StringReader(this.txtF.Text);
// Calls the Deserialize method and casts to the object type.
a= (A)mySerializer.Deserialize(sr);
wl("/r/n");
wl(a.ConnectionString);
wl("/r/n");
wl(a.AppPath);
wl("/r/n");
wl(a.PowerID.ToString());
}
结果:
bbb
aaa
99