2

我正在尝试向 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;
}

建议?

4

2 回答 2

3

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;
}
于 2012-11-12T06:49:08.960 回答
0

据我所知,你不能
在编译时提供属性。
属性是静态数据,您最好的选择可能是使用TypeDescriptor。(看TypeDescriptor.CreateProperty)也许你可以尝试创建一个具有必要属性的派生类?

编辑。看起来你可以!

在此处查看Marc Gravell 的回答

例子:

 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);
于 2012-11-12T04:19:37.467 回答