通常在 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/