[英]C# 4.0 Serialization of List<Customer>
在C#4.0中,我有一个称为“客户”的标准对象,它具有属性和公共的空构造函数。
我需要将一个通用的List<Customer>
序列化为XML,以便我可以保存它,然后加载它并反序列化它。
现在是否存在对此框架的支持,它比.NET 2.0中的支持更简单?
XmlSerializer对此框架提供了支持,它几乎没有变化,但非常易于使用。
Linq具有XML支持,但是IMO的System.Xml.Serialization
方式非常简单。 编写一个具有公共属性的类,如果它很简单,您甚至不需要对其进行注释。 只需创建一个序列化器并在其上使用流,就可以完成。
这是我在商品库中使用的内容:
public static string SerializeAsXml<TSource>(object element) where TSource : new()
{
return SerializeAsXml<TSource>(element, new Type[] {});
}
public static string SerializeAsXml<TSource>(object element, Type[] extraTypes) where TSource : new()
{
var serializer = new XmlSerializer(typeof(TSource), extraTypes);
var output = new StringBuilder();
using (StringWriter writer = new XmlStringWriter(output))
{
serializer.Serialize(writer, element);
}
return output.ToString();
}
public static TDestination Deserialize<TDestination>(string xmlPath) where TDestination : new()
{
return Deserialize<TDestination>(xmlPath, new Type[] { });
}
public static TDestination Deserialize<TDestination>(string xmlPath, Type[] extraTypes) where TDestination : new()
{
using (var fs = new FileStream(xmlPath, FileMode.Open))
{
var reader = XmlReader.Create(fs);
var serializer = new XmlSerializer(typeof(TDestination), extraTypes);
if (serializer.CanDeserialize(reader))
{
return (TDestination)serializer.Deserialize(reader);
}
}
return default(TDestination);
}
不是超级简单,但它的工作原理。 请注意,此操作仅从路径反序列化,但是您可以轻松地将其更改为从字符串反序列化,只需FileStream
。
XmlStringWriter
看起来像:
public class XmlStringWriter : StringWriter
{
public XmlStringWriter(StringBuilder builder)
: base(builder)
{
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
我只是在XML输出上强制使用UTF8编码。
序列化(将对象实例转换为XML文档):
// Assuming obj is an instance of an object
XmlSerializer ser = new XmlSerializer(obj.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
反序列化(将XML文档转换为对象实例):
//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(objType);
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
MyClass myObj = (MyClass)obj;
您还可以尝试msdn教程序列化(C#和Visual Basic)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.