EmitDefaultValue=false仅对字符串有效
本文关键字:字符串 有效 false EmitDefaultValue | 更新日期: 2023-09-27 18:04:09
我正在尝试将以下c#类序列化为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; }
}
当我使用以下代码序列化该类时
public static string GetLatLonPointXml(LatLonPoint data)
{
XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
using ( StringWriter stringWriter = new StringWriter() )
{
xmlSerializer.Serialize(stringWriter, data);
return stringWriter.ToString();
}
}
我得到以下结果
<?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>
当我添加了EmitDefaultValue到DataMember属性时,为什么要输出OptimalTime ?我已经能够让EmitDefaultValue与字符串一起工作,但不是其他任何东西。非常感谢您的帮助。
@Joe:谢谢!更改为DataContractSerializer修复了这个问题。现在我的序列化代码看起来像这样:
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);
}
}
现在的XML输出是:
<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>
谢谢Joe和Mr.EXE! Try This:
[DataContractFormat]
public class LatLonPoint
{
public float Lat { get; set; }
public float Lon { get; set; }
public DateTime? OptimalTime { get; set; }
}