Is there a way to get the ShouldSerialize*
pattern working with DataContractSerializer
?
Here is a small example:
I have a simple class Person
which 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
should only be serialized if they are not null or empty. This works with XmlSerializer
but DataContractSerializer
seems to ignore the ShouldSerialize
pattern. The *Specified
pattern also doesn't work.
I'm 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:est1.xml", settings))
{
serializer.WriteObject (writer, persons);
}
XmlSerializer xmlSerializer = new XmlSerializer (typeof (List<Person>));
XmlWriter xmlWriter = XmlWriter.Create (@"c:ext2.xml", settings);
xmlSerializer.Serialize (xmlWriter, persons);
xmlWriter.Close();
The output of the file 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 file test2.xml
(XmlSerializer) looks like this:
<?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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…