//根节点 humanResoure
[XmlRoot("humanResource")]
public class HumanResource
{
#region private data
private int m_record = 0;
//根节点 HumanResource 下面有work节点 将work定义为一个数组类型
private Worker[] m_workers = null;
#endregion
//xml属性 <humanResour record=''>
//AttributeName 属性名称
//
[XmlAttribute(AttributeName = "record")]
public int Record
{
get { return m_record; }
set { m_record = value; }
}
//定义一个元素 元素名称为worker workder下面的有number
[XmlElement(ElementName = "worker")]
public Worker[] workers
{
get { return m_workers; }
set { m_workers = value; }
}
}
//informationItem节点 informationItem下面还有节点
public class Worker
{
#region private data.
private string m_number = null;
//定义一个数组对象 Work下面的节点 informationItem
private InformationItem[] m_infoItems = null;
#endregion
//定义一个xml属性
[XmlAttribute("number")]
public string Number
{
get { return m_number; }
set { m_number = value; }
}
//定义一个xml元素
[XmlElement("infoItem")]
public InformationItem[] InfoItems
{
get { return m_infoItems; }
set { m_infoItems = value; }
}
}
//work下面的节点 InformationItem
public class InformationItem
{
#region priavte data
private string m_name = null;
private string m_value = null;
#endregion
//定义属性名称 在InfomationItem节点下
[XmlAttribute(AttributeName = "name")]
public string Name
{
get { return m_name; }
set { m_name = value; }
}
//定义xml文本节点
[XmlText]
public string Value
{
get { return m_value; }
set { m_value = value; }
}
}
//xml序列化方法
public sealed class ConfigurationManager
{
//单件模式 定义一个私有的构造函数 private 定义一个私有的类的对象
private static HumanResource m_humanResource = null;
private ConfigurationManager() { }
public static HumanResource Get(string path)
{
if (m_humanResource == null)
{
FileStream fs = null;
try
{
//序列化一个对象 HumanResource
XmlSerializer xs = new XmlSerializer(typeof(HumanResource));
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
m_humanResource = (HumanResource)xs.Deserialize(fs);
fs.Close();
return m_humanResource;
}
//处理异常
catch
{
if (fs != null)
fs.Close();
throw new Exception("Xml deserialization failed!");
}
}
else
{
return m_humanResource;
}
}
//将对象序列化成xml文件
public static void Set(string path,HumanResource humanResource)
{
FileStream fs = null;
if (humanResource == null)
{
throw new Exception("Parameter humanResource is null!");
}
try
{
//序列化对象 typeof要序列化对象的列名
XmlSerializer xs=new XmlSerializer(typeof(HumanResource));
fs = new FileStream(path,FileMode.Create,FileAccess.Write);
xs.Serialize(fs, humanResource);
m_humanResource = null;
fs.Close();
}
catch {
if (fs != null)
fs.Close();
throw new Exception("Xml serialization failed!");
}
}
}
序列化后产生xml文件格式如下:
<?xml version="1.0" ?>
<humanResource record="2">
<worker number="001">
<infoItem name="name">Michale</infoItem>
<infoItem name="sex">male</infoItem>
<infoItem name="age">25</infoItem>
</worker>
<worker number="002">
<infoItem name="name">Surce</infoItem>
<infoItem name="sex">male</infoItem>
<infoItem name="age">28</infoItem>
</worker>
</humanResource>