有没有办法让这个ShouldSerialize*
模式工作DataContractSerializer
?
这是一个小例子:
我有一个简单的类Person
,如下所示:
[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
或者LastName
仅当它们不为 null 或为空时才应序列化。这适用于XmlSerializer
但DataContractSerializer
似乎忽略了ShouldSerialize
模式。该*Specified
模式也不起作用。
我正在创建两个不同的 Xml 文件。一个带有 DataContractSerializer,一个带有 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();
文件test1.xml
(DataContractSerializer) 的输出如下所示:
<?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>
文件test2.xml
(XmlSerializer) 的输出如下所示:
<?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>