Search code examples
c#xml-serializationdatacontract

EmitDefaultValue=false only working for strings


I am trying to serialize the following c# class to XML

[DataContract]
public class LatLonPoint
{
  [DataMember(IsRequired = true, Order = 1)]
  public float Lat { get; set; }

  [DataMember(IsRequired = true, Order = 2)]
  public float Lon { get; set; }

  [DataMember(EmitDefaultValue = false, Order = 3)]
  public DateTime? OptimalTime { get; set; }
}

When I serialize this class using the following code

public static string GetLatLonPointXml(LatLonPoint data)
{
  XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());

  using ( StringWriter stringWriter = new StringWriter() )
  {
    xmlSerializer.Serialize(stringWriter, data);
    return stringWriter.ToString();
  }
}

I get the following result

<?xml version="1.0" encoding="utf-16"?>
<LatLonPoint xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Lat>30</Lat>
  <Lon>-97</Lon>
  <OptimalTime xsi:nil="true" />
</LatLonPoint>

Why is the OptimalTime being output when I have added the EmitDefaultValue to the DataMember attribute? I have been able to get EmitDefaultValue to work with strings, but not anything else. Thank you very much for your help.


Solution

  • @Joe: Thanks! Changing to the DataContractSerializer fixed the issue. Now my serialization code looks like this:

    public static string GetXml(LatLonPoint data)
    {
      DataContractSerializer serializer = new DataContractSerializer(data.GetType());
    
      using ( MemoryStream stream = new MemoryStream() )
      {
        serializer.WriteObject(stream, data);
        byte[] bytes = stream.ToArray();
        return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
      }
    }
    

    The XML output is now:

    <LatLonPoint xmlns="http://schemas.datacontract.org/2004/07/Mnc.Service.Model.External" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Lat>30</Lat>
      <Lon>-97</Lon>
    </LatLonPoint>
    

    Thanks Joe and Mr.EXE!