XML 序列化

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值