C#如何把类CLASS实例进行序列化及反序列化为XML文件

2020-08-12 22:45

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:
C#如何把类Class实例进行序列化及反序列化为XML文件

.NET 2.0中可以很方便得把一个类序列化为XML文件,需要生成XML文件功能可以通过此操作实现。

首先定义数据类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Xml.Serialization;

namespace Class2XML
{
public class DataClass
{
private String PersonName;
private int PersonAge;
private double PersonWeight;
private ArrayList Relations;
private Bitmap PersonPhoto;
[XmlElement(ElementName = “Picture“)]
public String ImageStr;

public string PersonName1
{
get { return PersonName; }
set { PersonName = value; }
}

public int PersonAge1
{
get { return PersonAge; }
set { PersonAge = value; }
}

public double PersonWeight1
{
get { return PersonWeight; }
set { PersonWeight = value; }
}

public ArrayList Relations1
{
get { return Relations; }
set { Relations = value; }
}

public Bitmap PersonPhoto1
{
get { return PersonPhoto; }
set { PersonPhoto = value; }
}

public DataClass()
{
Relations = new ArrayList();

}
}
}

调用部分代码片断:

//--设置
String filename = “test.xml“;
TextWriter writer = new StreamWriter(filename);
//--设置数据类属性
DataClass Person = new DataClass();
Person.PersonName1 = “Song Xiaobin“;
Person.PersonAge1 = 30;
Person.PersonWeight1 = 1.24;
Person.Relations1.Add(“Ye Ying“);
Person.Relations1.Add(“Wang kun“);
Person.Relations1.Add(“Lu Qinghu“);
Person.PersonPhoto1 = new Bitmap(“C:\\Documents and Settings\\hbl6032\\My Documents\\My Pictures\\insite_core02.bmp“);
//--处理位图数据
System.IO.MemoryStream ImageStream = new System.IO.MemoryStream();
Person.PersonPhoto1.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
Person.ImageStr = System.Convert.ToBase64String(ImageStream.GetBuffer());
//--序列化到XML
XmlSerializer serializer = new XmlSerializer(Person.GetType());
serializer.Serialize(writer, Person);
writer.Close();

通过以上操作可以把C#类序列化为XML,其中位图通过字符串存储,恢复的时候需要从64位字符串转换为字节内容。

从XML反序列化的操作类似于上面的内容。