我正在尝试向XmlSerializor添加一些提示,以便它可以序列化/反序列化接口。我不能在课堂上添加XmlIncludeAttribute作为装饰,而是希望将序列化覆盖传递给XmlSerializor:
var _xs = new XmlSerializer(typeof(Model.ISession), SerializationOverrides());
SerializationOverrides()
看起来像这样:
private static XmlAttributeOverrides SerializationOverrides()
{
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Model.ISession), XmlInclude(typeof(Model.Session)));
return overrides;
}
到目前为止,这么好。 XmlInclude(...)
方法会创建一个新的XmlAttributes对象,但我无法弄清楚如何添加XmlIncludeAttribute属性。
private static XmlAttributes XmlInclude(Type type)
{
var attrs = new XmlAttributes();
attrs....Add(new XmlIncludeAttribute(type)); // Add how?????
return attrs;
}
建议?
答案 0 :(得分:2)
XmlSerializer构造函数可以接受一个“额外类型”数组,如下所示:
var _xs = new XmlSerializer(typeof(Model.ISession),
SerializationOverrides(), new Type[] { typeof(Model.Session),
new XmlRootAttribute("Session"), "");
这样做以及向覆盖添加额外的XmlElements似乎就是这样做的:
private static XmlAttributeOverrides SerializationOverrides()
{
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Model.ISession), XmlInclude("Session", typeof(Model.Session)));
return overrides;
}
private static XmlAttributes XmlInclude(string name, Type type)
{
var attrs = new XmlAttributes();
attrs.XmlElements.Add(new XmlElementAttribute(name, type));
return attrs;
}
答案 1 :(得分:0)
据我所知,你不能
您必须在编译时提供属性
属性是静态数据,您最好的选择可能是使用TypeDescriptor。 (看TypeDescriptor.CreateProperty
)
您可以尝试创建具有必要属性的派生类吗?
修改。看起来你可以!
示例:
var aor = new XmlAttributeOverrides();
var Attribs = new XmlAttributes();
Attribs.XmlElements.Add(new XmlElementAttribute("Session", typeof(Model.Session)));
aor.Add(typeof(type), "Models", listAttribs);
XmlSerializer ser = new XmlSerializer(typeof(type), aor);