Serialize an object to XML without using attributes



How can I use XmlSerializer/DataContractSerializer to serialize an object which class does not specify any serialization attributes?


Some use cases:



  • A large existing class, which I don't wish to pollute with serialization attributes

  • Serializing a class for which no source code is available

  • Switching from using XmlSerializer to DataContractSerializer to JSON without changing class code


For example, how would I serialize the following without uncommenting the attributes:



// [Serializable]
public MyClass
{
// [XmlIgnore] - uncommenting this would be the easy way
public int DontSerializeMeEvenThoughImPublic { get; set; }

// [XmlAttribute] - uncommenting this would be the easy way
public double SerializeMeAsXmlAttribute { get; set; }
}

No comments:

Post a Comment