【问题标题】:Declaratively define xml serialization using pocos使用 pocos 以声明方式定义 xml 序列化
【发布时间】:2011-01-20 09:48:08
【问题描述】:

通常在 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,我可能会重用这些属性来进行 OR-Mapping,例如NHibernate,那么最好在不改变要序列化的类型的情况下定义序列化方式。

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

【问题讨论】:

标签: c# xml serialization xml-serialization mapping


【解决方案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 对象,因为每个对象都会创建一个无法卸载的动态序列化程序集。如果你不缓存和重用,你会淹没内存。

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2010-12-25
    相关资源
    最近更新 更多