2

I'm trying to add some hints to the XmlSerializor so it can serialize/deserialize interfaces. I can't add the XmlIncludeAttribute as a decoration on the class, in stead I want to pass in serialization overrides to the XmlSerializor:

var _xs = new XmlSerializer(typeof(Model.ISession), SerializationOverrides());

The SerializationOverrides() looks like this:

private static XmlAttributeOverrides SerializationOverrides()
{
    var overrides = new XmlAttributeOverrides();

    overrides.Add(typeof(Model.ISession), XmlInclude(typeof(Model.Session)));

    return overrides;
}

So far, so good. The XmlInclude(...) method creates a new XmlAttributes object, but I can't figure out how to add the XmlIncludeAttribute attribute.

private static XmlAttributes XmlInclude(Type type)
{
    var attrs = new XmlAttributes();

    attrs....Add(new XmlIncludeAttribute(type)); // Add how?????

    return attrs;
}

Suggestions?

Jakob Gade
  • 12,319
  • 15
  • 70
  • 118

2 Answers2

3

The XmlSerializer constructor can accept an array of "extra types", like this:

var _xs = new XmlSerializer(typeof(Model.ISession), 
    SerializationOverrides(), new Type[] { typeof(Model.Session), 
    new XmlRootAttribute("Session"), "");

Doing that as well as adding additional XmlElements to the overrides seems to be doing the trick:

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;
}
Jakob Gade
  • 12,319
  • 15
  • 70
  • 118
0

From best of my knowledge, you can't
You have to provide attributes at compile time.
Attributes are static data and your best bet would probably be using TypeDescriptor. (Look at TypeDescriptor.CreateProperty) Probably you can try to create a derived class with necessary attributes?

EDIT. Looks like you can!

See Marc Gravell answer here

example:

 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);
Community
  • 1
  • 1
RAS
  • 3,375
  • 15
  • 24