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

阅读更多
个人分类: 代码收藏
上一篇project,psp,rup,uml
下一篇DNN学习资料
想对作者说点什么? 我来说一句

serializer

2018年05月30日 270KB 下载

XML序列化示例 XML

2008年12月08日 7KB 下载

二进制序列化XML序列化

2012年06月13日 34KB 下载

没有更多推荐了,返回首页

关闭
关闭
关闭