C#实现Xml序列化与反序列化的方法
本文实例讲述了c#实现xml序列化与反序列化的方法。分享给大家供大家参考。具体实现方法如下:
/// xml序列化与反序列化
/// </summary>
public class xmlutil
{
public static string getroot(string xml)
{
xmldocument doc = new xmldocument();
doc.loadxml(xml.replace("\r\n", "").replace("\0", "").trim());
var e = doc.documentelement;
return e.innertext;
}
#region 反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="xml">xml字符串</param>
/// <returns></returns>
public static t deserialize<t>(string xml)
{
return (t)deserialize(typeof(t), xml);
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="stream">字节流</param>
/// <returns></returns>
public static t deserialize<t>(stream stream)
{
return (t)deserialize(typeof(t), stream);
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">xml字符串</param>
/// <returns></returns>
public static object deserialize(type type, string xml)
{
try
{
xml = xml.replace("\r\n", "").replace("\0", "").trim();
using (stringreader sr = new stringreader(xml))
{
xmlserializer xmldes = new xmlserializer(type);
return xmldes.deserialize(sr);
}
}
catch (exception e)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object deserialize(type type, stream stream)
{
xmlserializer xmldes = new xmlserializer(type);
return xmldes.deserialize(stream);
}
#endregion
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string serializer<t>(t obj)
{
return serializer(typeof(t), obj);
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string serializer(type type, object obj)
{
memorystream stream = new memorystream();
xmlserializernamespaces _name = new xmlserializernamespaces();
_name.add("", "");//这样就 去掉 attribute 里面的 xmlns:xsi 和 xmlns:xsd
xmlwritersettings xmlwritersettings = new xmlwritersettings();
xmlwritersettings.encoding = new utf8encoding(false);//设置编码,不能用encoding.utf8,会导致带有bom标记
xmlwritersettings.indent = true;//设置自动缩进
//xmlwritersettings.omitxmldeclaration = true;//删除xmldeclaration:<?xml version="1.0" encoding="utf-16"?>
//xmlwritersettings.newlinechars = "\r\n";
//xmlwritersettings.newlinehandling = newlinehandling.none;
xmlserializer xml = new xmlserializer(type);
try
{
using (xmlwriter xmlwriter = xmlwriter.create(stream, xmlwritersettings))
{
//序列化对象
xml.serialize(xmlwriter, obj, _name);
}
}
catch (invalidoperationexception)
{
throw;
}
return encoding.utf8.getstring(stream.toarray()).trim();
}
#endregion
}
希望本文所述对大家的c#程序设计有所帮助。