使用pocos声明性地定义xml序列化

时间:2011-01-20 09:48:09

标签: c# xml serialization xml-serialization mapping

通常在C#中,Xml类型用属性标记,以定义它们的获取方式 序列:

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(Namespace=
"urn:xmlns:25hoursaday-com:my-bookshelf")]
public class bookType {

    /// <remarks/>
    public string title;

    /// <remarks/>
    public string author;

   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("publication-date", 
DataType="date")]      
    public System.DateTime publicationdate;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string publisher;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute("on-loan")]
    public string onloan;
}

现在谈到我喜欢使用没有这些属性的POCOS时,我可能会重复使用P-OS进行OR映射。 NHibernate,那么以一种方式定义序列化方式而不改变要序列化的类型会很好。

问题是:有没有办法让declerativeley定义一个类型被序列化的方式,例如:映射xml文件。

1 个答案:

答案 0 :(得分:1)

是:

    XmlAttributeOverrides attribs = new XmlAttributeOverrides();
    attribs.Add(typeof(bookType), new XmlAttributes
    {
        XmlType = new XmlTypeAttribute { Namespace = "urn:xmlns:25hoursaday-com:my-bookshelf" },
    });
    attribs.Add(typeof(bookType), "publicationdate", new XmlAttributes
    {
        XmlElements = { new XmlElementAttribute("publication-date") { DataType = "date" } }
    });
    attribs.Add(typeof(bookType), "publisher", new XmlAttributes
    {
        XmlAttribute = new XmlAttributeAttribute()
    });
    attribs.Add(typeof(bookType), "onloan", new XmlAttributes
    {
        XmlAttribute = new XmlAttributeAttribute("on-loan")
    });

然后序列化:

    XmlSerializer s = new XmlSerializer(typeof(bookType), attribs);
    var obj = new bookType { title = "a", author = "b",
        publicationdate = DateTime.Now, publisher = "c", onloan = "d"};
    s.Serialize(Console.Out, obj);

无论其

我不能过分强调这一点;您必须缓存并重新使用以这种方式创建的XmlSerializer对象,因为每个对象都会创建无法卸载的动态序列化程序集。如果你不缓存和重复使用,你就会淹没内存。