如何实现XML序列化的自定义类型? [英] How to implement xml serialization for custom types?

查看:152
本文介绍了如何实现XML序列化的自定义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类型的,我想序列化/反序列化,并基于所选对象的UI。用户界面也将发生变化从而我将不得不序列化将其存储在我的应用程序的对象。

I have some types that I want to serialize/deserialize and generate a UI based on the selected object. The UI will also change the object which in turn I will have to serialize to store it in my app.

所以:

[obj_apple stored in the app] -> select obj_apple -> deserialize -> show in UI -> use the UI to change obj_apple -> deselect obj_apple -> serialize -> [obj_apple stored in the app]

中的对象必须进行序列化/反序列化,并将这些数据必须是字符串。这就是为什么我认为有一个XML序列化会更好。

The objects have to be serialized/deserialized and this data has to be string. That's why I thought having an xml serializer would be better.

哪种类型的序列化将是最好的?而且在那里实现这个自定义类型的任何好的例子?

Which type of serializer would be the best? And are there any good examples to implement this for custom types?

推荐答案

您有串几个选择; XML,它可以简单地用的XmlSerializer 来完成(或的DataContractSerializer ,但提供更少的控制权XML)或JSON(JSON.net等)。

You have a few choices for strings; xml, which can be done simply with XmlSerializer (or DataContractSerializer, but that offers much less control over the xml) or JSON (JSON.net, etc).

典型的类的XmlSerializer 看起来只是想:

Typical classes for XmlSerializer would look simply like:

public class Apple {
    public string Variety {get;set;}
    public decimal Weight {get;set;}
    // etc
}

(注意:我希望上述工作的JSON.net太)

(note I would expect the above to work the JSON.net too)

以上级也应该在数据绑定方案等做工精细,由于属性。

The above class should also work fine in data-binding scenarios etc, thanks to the properties.

您将序列如下:

    Apple obj = new Apple { Variety = "Cox", Weight = 12.1M};
    XmlSerializer ser = new XmlSerializer(typeof(Apple));

    StringWriter sw = new StringWriter();
    ser.Serialize(sw, obj);
    string xml = sw.ToString();

    StringReader sr = new StringReader(xml);
    Apple obj2 = (Apple)ser.Deserialize(sr);

但你可以自定义XML:

but you can customize the xml:

[XmlType("apple"), XmlRoot("apple")]
public class Apple {
    [XmlAttribute("variety")]
    public string Variety {get;set;}
    [XmlAttribute("weight")]
    public decimal Weight {get;set;}
    // etc
}

的DataContractSerializer 理想的更像是:

[DataContract]
public class Apple {
    [DataMember]
    public string Variety {get;set;}
    [DataMember]
    public decimal Weight {get;set;}
}

这篇关于如何实现XML序列化的自定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆