2

With a model such as ..

class Base {
  public Child Child { get; set; }
}
class Child {
  public int Id { get; set; }
  // other properties
}

I want to do Xml Serialization, but for the Child object on Base, I only want to serialize the Id property. The rest of the Child object will be serialized into its own separate file. Is this possible to do without making two sets of models?

Ciel
  • 17,312
  • 21
  • 104
  • 199

2 Answers2

1

You could possibly use the XmlIgnore attribute on all of the other properties. Not sure if that will get the result you're after.

Matthew Steeples
  • 7,858
  • 4
  • 34
  • 49
1

If you only serialize Child in the context of Base, you can mark the other members with [XmlIgnore] and they won't appear.

If you need a different layout in different contexts, then you can use XmlAttributeOverrides to define the model at runtime, but this isn't trivial. Also, if doing this you MUST cache and re-use the resulting XmlSerializer (there is a ctor that accepts the overrides), or it will leak dynamic assemblies (there is an inbuilt cache for the trivial typeof(SomeRoot) serializers, but custom serializers are not automatically cached, and generate an assembly each; assemblies cannot be unloaded).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900