我有以下数据合同:
namespace Wcf.Contracts.Data
{
[DataContract]
public class Presence
{
[DataMember]
public int Id { get; set; }
[DataMember]
public DateTime? From { get; set; }
[DataMember]
public DateTime? To { get; set; }
[DataMember]
public TimeSpan? BreakPeriod { get; set; }
}
}
将 的实例Presence
序列化为 XML 并将相同的 XML 反序列化回 的实例Presence
效果很好。但是反序列化一个代表序列化Presence
对象的字符串变量给了我奇怪的行为。某些属性从 XML 获取默认值而不是指定值。我发现 XML 中代表属性的元素Presence
必须按字母顺序排列。
例如在这段代码中
var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(Wcf.Contracts.Data.Presence));
var xml1 = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Presence xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Wcf.Contracts.Data"">
<BreakPeriod>PT30M</BreakPeriod>
<From>2013-08-21T10:00:00Z</From>
<To>2013-08-21T15:00:00Z</To>
<Id>85</Id>
</Presence>";
var xr1 = System.Xml.XmlReader.Create(new System.IO.StringReader(xml1));
var p1 = dcs.ReadObject(xr1) as Wcf.Contracts.Data.Presence;
var xml2 = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Presence xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Wcf.Contracts.Data"">
<Id>85</Id>
<From>2013-08-21T10:00:00Z</From>
<To>2013-08-21T15:00:00Z</To>
<BreakPeriod>PT30M</BreakPeriod>
</Presence>";
var xr2 = System.Xml.XmlReader.Create(new System.IO.StringReader(xml2));
var p2 = dcs.ReadObject(xr2) as Wcf.Contracts.Data.Presence;
var xml3 = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Presence xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Wcf.Contracts.Data"">
<BreakPeriod>PT30M</BreakPeriod>
<From>2013-08-21T10:00:00Z</From>
<Id>85</Id>
<To>2013-08-21T15:00:00Z</To>
</Presence>";
var xr3 = System.Xml.XmlReader.Create(new System.IO.StringReader(xml3));
var p3 = dcs.ReadObject(xr3) as Wcf.Contracts.Data.Presence;
这三个实例都是不同的。
| p1 | p2 | p3
Id | default(int) (=0) | 85 | 85
From | 8/21/2013 10:00:00 AM | default(DateTime?) (=null) | 8/21/2013 10:00:00 AM
To | 8/21/2013 3:00:00 PM | 8/21/2013 3:00:00 PM | 8/21/2013 3:00:00 PM
BreakPeriod | 00:30:00 | default(TimeSpan?) (=null) | 00:30:00
为什么必须对 XML 中的元素进行排序?有谁知道为什么DataContractSerializer
否则不能正确反序列化?