Is there a way to get a ShouldSerialize* template working with a DataContractSerializer ?
Here is a small example:
I have a simple Person class that looks like this:
[DataContract] public class Person { [DataMember] public string FirstName { get; set; } public bool ShouldSerializeFirstName() { return !string.IsNullOrEmpty(FirstName); } [DataMember] public string LastName { get; set; } public bool ShouldSerializeLastName() { return !string.IsNullOrEmpty(LastName); } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public Person(string firstName) { FirstName = firstName; } public Person() { } }
FirstName or LastName must be serialized if they are not empty or empty. This works with the XmlSerializer , but the DataContractSerializer seems to ignore the ShouldSerialize pattern. *Specified template also does not work.
I am creating two different xml files. One with DataContractSerializer, one with XmlSerializer:
List<Person> persons = new List<Person>(); persons.Add (new Person("John", "Doe")); persons.Add (new Person("Carl")); DataContractSerializer serializer = new DataContractSerializer (typeof (List<Person>)); using (XmlWriter writer = XmlWriter.Create(@"c:\test1.xml", settings)) { serializer.WriteObject (writer, persons); } XmlSerializer xmlSerializer = new XmlSerializer (typeof (List<Person>)); XmlWriter xmlWriter = XmlWriter.Create (@"c:\text2.xml", settings); xmlSerializer.Serialize (xmlWriter, persons); xmlWriter.Close();
The output of test1.xml (DataContractSerializer) looks like this:
<?xml version="1.0" encoding="utf-8"?> <ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/XmlSerialization"> <Person> <FirstName>John</FirstName> <LastName>Doe</LastName> </Person> <Person> <FirstName>Carl</FirstName> <LastName i:nil="true" /> </Person> </ArrayOfPerson>
The output of test2.xml (XmlSerializer) is as follows:
<?xml version="1.0" encoding="utf-8"?> <ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Person> <FirstName>John</FirstName> <LastName>Doe</LastName> </Person> <Person> <FirstName>Carl</FirstName> </Person> </ArrayOfPerson>
source share