I am trying to serialize a List<T> where T: EntityObject and would love to leave out all the EntityKey and other EntityReference properties from the items in the list. Can this be done dynamically possibly using XmlAttributeOverrides?
As far as I can see, the XmlAttributeOverrides options only really point to the top level object ie the List<T> and not the T themselves, which is not very helpful to me. Could anyone point me to a way to dynamically ignore properties of ArrayItems?
Here is a simple example I have been using that does not use EntityObjects but it should illustrate what I would like to do:
public class Car
{
public String Make { get; set; }
public String Model { get; set; }
public Double EngineSize { get; set; }
}
[Test]
public void WouldLoveToDynamicallyLeaveOutMembersOfArrayItems()
{
var cars = new List<Car>
{
new Car
{
Make = "Ferrari",
Model = "F1",
EngineSize = 6000
},
new Car
{
Make = "Williams",
Model = "F1",
EngineSize = 5500
}
};
var attributeOverrides = new XmlAttributeOverrides();
attributeOverrides.Add(typeof(Double), "EngineSize", new XmlAttributes {XmlIgnore = true});
var xs = new XmlSerializer(cars.GetType(), attributeOverrides, new []{ typeof(Car) }, new XmlRootAttribute("cars"), "");
var ms = new MemoryStream();
xs.Serialize(ms, cars);
ms.Position = 0;
var sr = new StreamReader(ms);
var result = sr.ReadToEnd();
Assert.IsFalse(result.Contains("EngineSize"));
}
Yes you can do that - the main error is you need typeof(Car) instead of typeof(double). With this, note that XmlAttributeOverrides does not just apply to the top-level onject.
However, I'm not sure that is the easiest route. Firstly, note that you must store and re-use the serialiser when using XmlAttributeOverrides otherwise you will leak assemblies.
I expect the main reason you want to do this is because you don't want to edit he generated file. However, there is another way; in a separate file, in the right namespace, you can use:
Where "ShouldSerialize*" is a pattern recognised and used by XmlSerializer to control conditional serialization. The "partial" class is simply a way of combining two separate code files into a single type (and was designed for this generated-content scenario).
This way, you dont need to mess with XmlAttributeOverrides, and you can use the simpler "new XmlSeralizer(Type)" (which has automatic caching per-type).