I have a c# object Person as a property inside another object Appointment. My Person object has properties ID, FirstName, LastName. I am currently serializing appointment into XML, but when it comes to the nested Person object, I would only like ID, to be serialized. Is there a way to specify this from the Appointment class?
I simply can't go into Person and mark FirstName and LastName as non-serializable fields, because I need to serialize person in other instances within my solution.
I am hopi开发者_如何学Gong to find something where I can have this:
public class Appointment {
[SerializeProperty("ID")]
public Person MyPerson {
get;
set;
}
}
Any thoughts?
You can do something like this:
public class Appointment
{
[XmlIgnore()]
public Person MyPerson
{
get;
set;
}
public int MyPersonId
{
get { return MyPerson.Id; }
set { MyPerson = new Person(value)}
}
}
You can have Person implement IXmlSerializable to do it's custom serialization (dumping only the ID, e.g.)
Or you can implement it for your Appointment instead, making it trivial to select exactly the bits you want serialized.
As a hybrid option, you can delegate the implementation of such a custom serializer to a helper struct that you can construct to mimick the exact serialization layout you want to have. This way, you won't have to deal with details and the XmlWriter
HTH
精彩评论