1 反序列化函数定义
public object deSerialize(string filePath, Type type)
{
object t = null;
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
t = xmlSerializer.Deserialize(reader);
}
}
return t;
}
2 序列化函数定义
public void saveToXml(string filePath, object sourceObj, Type type, string rootName)
{
if (File.Exists(filePath) && sourceObj != null)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
type = type != null ? type : sourceObj.GetType();
System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(rootName) ?
new System.Xml.Serialization.XmlSerializer(type) : new System.Xml.Serialization.XmlSerializer(type, new System.Xml.Serialization.XmlRootAttribute(rootName));
xmlSerializer.Serialize(writer, sourceObj);
}
}
}
解释:
filename 是 xml 文件的根目录
sourceObj 是源对象 一般为类的一个对象
type 为 源对象的类型
rootname 为根文件名 可自定义 也可不自定义
一个复杂的xml文件如下
This XML file does not appear to have any style information associated with it. The document tree is shown below.euoqejadj //element 水平结构NIKE //root // element //list root // element // list root 429485-95478025402502 //xmlAttribute (...baidu.com) 42....是xmlText 429485-95478025402502 429485-95478025402502 429485-95478025402502
其中 :
List
参考:
C#对象XML序列化(一):序列化方法和常用特性 - K.W - 博客园



