作者:世卍界创意驿站肀 | 来源:互联网 | 2023-10-10 07:54
定义一个需要序列化的对象:
using System; namespace XMLSerializer
{
/// ﹤summary﹥
/// 测试类
/// ﹤/summary﹥
public class TestXML
{
public string name;
public string sex;
public string age;
}
}
然后我们就可以在程序中使用这个类构造对象 c# XML序列化。
private void button1_Click( object sender, System.EventArgs e)
{
TestXML a = new TestXML();
a.name = tbName.Text;
a.sex = tbSex.Text;
a.age = tbAge.Text;
SaveFileDialog of = new SaveFileDialog();
of.Filter = " XML文档|*.XML";
if( of.ShowDialog() == DialogResult.OK )
{
try { Stream s = of.OpenFile();
new XmlSerializer( a.GetType() ).Serialize( s, a );
s.Close();
}
catch( Exception ex )
{
MessageBox.Show( ex.Message );
}
}
}
C# XML序列化之从XML文档中反序列化出对象
private void button2_Click(object sender, System.EventArgs e)
{
OpenFileDialog o = new OpenFileDialog();
o.Filter = " XML文档|*.XML|所有文件|*.*";
if( o.ShowDialog() == DialogResult.OK )
{
try
{
XmlSerializer xs = new XmlSerializer( typeof( TestXML )
);
Stream s = o.OpenFile();
TestXML a = xs.Deserialize( s ) as TestXML;
tbName.Text = a.name;
tbSex.Text = a.sex;
tbAge.Text = a.age;
s.Close();
}
catch( Exception ex )
{
MessageBox.Show( ex.Message );
}
}
}