EmitDefaultValue=false only working for strings

折月煮酒 提交于 2021-02-11 17:57:20

问题


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.


回答1:


@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!




回答2:


Try This:

 [DataContractFormat]

 public class LatLonPoint
{

    public float Lat { get; set; }


    public float Lon { get; set; }


    public DateTime? OptimalTime { get; set; }
}


来源:https://stackoverflow.com/questions/23742805/emitdefaultvalue-false-only-working-for-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!