4

有没有办法让这个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 或为空时才应序列化。这适用于XmlSerializerDataContractSerializer似乎忽略了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>
4

2 回答 2

5

AFAIK,ShouldSerialize* 不适用于数据合同序列化程序。凯文的回答是没用的。你可以删除它。不幸的是,给出的代码仅在您处理空值时才有效。

这是一个更通用的解决方案:它根据给定条件返回空值。

    [DataContract]
    public class Person
    {
      private string firstName;
      [DataMember(IsRequired = false, EmitDefaultValue = false)]
      public string FirstName
      {
        get
        {
            //Put here any condition for serializing
            return string.IsNullOrWhiteSpace(firstName) ? null : firstName;
        }
        set
        {
            firstName = value;
        }
      }
    }
于 2014-04-28T08:32:13.637 回答
4

您应该在 DataMember 上设置 IsRequired 属性:

[DataContract]
public class Person
{
  [DataMember(IsRequired = False, EmitDefaultValue = False)]
  public string FirstName { get; set; }
  ...
}
于 2012-07-09T12:02:54.820 回答