C# XML序列化實(shí)例淺析
作者:applesina
C# XML序列化實(shí)例向你展現(xiàn)了一個實(shí)現(xiàn)C# XML序列化的Demo,那么實(shí)現(xiàn)C# XML序列化具體的操作方法是什么呢?那么本文向你介紹具體的內(nèi)容。
實(shí)現(xiàn)C# XML序列化技術(shù)使用到什么具體的方法呢?我們在具體的操作過程中需要注意什么呢?那么這里向你展示一個Demo,希望對你了解C# XML序列化技術(shù)有所幫助。
首先,我們定義一個需要序列化的對象:
- using System;
- namespace XMLSerializer
- {
- /// ﹤summary﹥
- /// 測試類
- /// ﹤/summary﹥
- public class TestXML
- {
- public string name;
- public string sex;
- public string age;
- }
- }
然后我們就可以在程序中使用這個類構(gòu)造對象,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 );
- }
- }
- }
C# XML序列化的具體實(shí)現(xiàn)實(shí)例就向你介紹到這里,希望那個對你了解和學(xué)習(xí)C# XML序列化有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來源:
百度空間