www.pudn.com > PlanBoard.rar > XMLFactory.cs
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
using System.Collections;
namespace PlanBoard
{
///
/// XMLFactory 的摘要说明。
///
public class XMLFactory
{
public XMLFactory()
{
}
///
/// 将可序列化实例保存为XML文件
///
/// 可序列化实例
/// 文件路径
///
public string SaveInfoByXml(object obj, string path, Type type)
{
string rtn = "保存配置文件成功";
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.Default);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 4;
XmlSerializer serializer = new XmlSerializer(type);
try
{
serializer.Serialize(xmlWriter, obj);
}
catch(Exception e)
{
rtn = "保存配置文件失败,Failed to serialize. Reason: " + e.Message;
}
finally
{
stream.Close();
}
return rtn;
}
///
/// 读取XML文件并返回实例
///
/// 可序列化实例
/// 文件路径
///
public string LoadInfoByXml(out object obj, string path, Type type)
{
string rtn = "读取配置文件成功";
obj = null;
Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
XmlSerializer serializer = new XmlSerializer(type);
try
{
obj = serializer.Deserialize(stream);
}
catch(Exception e)
{
rtn = "读取配置文件失败,Failed to deserialize. Reason: " + e.Message;
}
finally
{
stream.Close();
}
return rtn;
}
///
/// 将XML格式化保存
///
/// 保存文件的路径
/// XML内容
public void WriteByFormat(string filePath, string strXml)
{
XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXml);
doc.WriteTo(writer);
writer.Close();
}
}
}