我正在尝试将以下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来处理字符串,但不能用其他任何东西。非常感谢你的帮助。
答案 0 :(得分:1)
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!
答案 1 :(得分:0)
试试这个:
[DataContractFormat]
public class LatLonPoint
{
public float Lat { get; set; }
public float Lon { get; set; }
public DateTime? OptimalTime { get; set; }
}