I’m trying to write a generic method to serialize an object that inherits from my ITable interface. I would also like to have a parameter of PropertyInfo[] where I can specify the properties that need to be serialized with the object. Those that are not present are ignored. Is there a way to tell the XmlSerialize to only serialize those properties listed?
Method signature:
public static string SerializeToXml<T>(T obj, PropertyInfo[] fields = null) where T : ITable
If fields is null, Automatically grab all fields.
if (fields == null)
{
Type type = typeof(T);
fields = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
Normally, you would do this using attributes, specifically, you can add the
[XmlIgnore]attribute to properties you don’t want to serialize (notice that this is the other way around to what you want).But since you want to do this at runtime, you can use the
XmlAttributeOverridesclass to, you guessed it, override the attributes at runtime.So, something like this should work:
On an unrelated note, I think naming a parameter that contains properties
fieldsis highly confusing.