xml序列化与反序列化
public static void Serialize(ParseResult parseResult)
{
var filePath = Path.Combine(CachePath, parseResult.ParseTime + ".xml");
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
var ds = new XmlSerializer(typeof(ParseResult));
var settings = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create(filePath, settings))
{
ds.Serialize(writer, parseResult);
}
}
public static ParseResult Deserialize(string fileName)
{
try
{
var serializer = new XmlSerializer(typeof(ParseResult));
var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
var parseResult = serializer.Deserialize(stream) as ParseResult;
stream.Close();
return parseResult;
}
catch
{
return null;
}
}
public static void Serialize<T>(T parseResult, string fileName)
{
var filePath = Path.Combine(DirectoryPath, fileName);
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
var ds = new XmlSerializer(typeof(T));
var settings = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create(filePath, settings))
{
ds.Serialize(writer, parseResult);
}
}
public static T Deserialize<T>(string fileName)
{
try
{
var serializer = new XmlSerializer(typeof(T));
var stream = new FileStream(Path.Combine(DirectoryPath, fileName), FileMode.Open, FileAccess.Read);
var parseResult = (T)serializer.Deserialize(stream);
stream.Close();
return parseResult;
}
catch (Exception exception)
{
return default(T);
}
}
public static string Serialize<T>(T parseResult)
{
try
{
var buffer = new StringBuilder();
var ds = new XmlSerializer(typeof(T));
using (var writer = new StringWriter(buffer))
{
ds.Serialize(writer, parseResult);
}
return buffer.ToString();
}
catch (Exception)
{
return string.Empty;
}
}
作者:Jackhuclan
出处:http://jackhuclan.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://jackhuclan.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。