c# - 使用 pocos 以声明方式定义 xml 序列化

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

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

最佳答案

是的:

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

关于c# - 使用 pocos 以声明方式定义 xml 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4745579/

相关文章:

java - ListView 中的可点击项目

java - Spark 序列化的奇怪之处

java - 错误 : Class declares multiple JSON fields named serialVersionUid

c# - 这个 Dapper 查询总是返回 null

java - 在 JAXB 中注册所有对象创建事件

c# - Entity Framework 中的 Linq 查询优化

xml - 为 F# 记录值生成的 IntelliSense XML 不正确 (VS2013)

java - 在 Java 中使异常字段成为 transient

c# - 数组索引选择 C#

C# 在运行时使用字符串创建表达式