C#4.0 List <customer> </customer>的序列化

时间:2011-03-30 01:49:51

标签: c# c#-4.0 .net-4.0 xml-serialization

在C#4.0中,我有一个名为“Customer”的标准对象,它有属性和公共空构造函数。

我需要将通用List<Customer>序列化为XML,以便保存,然后加载并反序列化。

现在是否有比这更简单的框架支持?

4 个答案:

答案 0 :(得分:3)

对此的框架支持是XmlSerializer,它基本上没有变化,但很容易使用。

答案 1 :(得分:2)

Linq有XML支持,但IMO System.Xml.Serialization方式非常简单。写一个带有公共属性的类,如果它很简单,你甚至不需要注释它。只需制作一个序列化程序并在其上使用流,就可以了。

答案 2 :(得分:2)

这是我在我的好东西库中使用的内容:

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编码。

答案 3 :(得分:0)

Serialize(将对象实例转换为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教程 Serialization (C# and Visual Basic)