数据合同序列化不适用于所有元素

时间:2010-03-26 19:58:52

标签: c# xml serialization datacontractserializer

我有一个XML文件,我正在尝试序列化为一个对象。有些元素被忽略了。

我的XML文件:

<?xml version="1.0" encoding="utf-8" ?> 
<License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain">
<Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> 
<Url>http://www.gmail.com</Url> 
<ValidKey>true</ValidKey> 
<CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> 
<RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> 
<ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> 
</License>

我的班级定义:

[DataContract]
public class License
{
    [DataMember]
    public virtual int Id { get; set; }
    [DataMember]
    public virtual string Guid { get; set; }
    [DataMember]
    public virtual string ValidKey { get; set; }
    [DataMember]
    public virtual string Url { get; set; }
    [DataMember]
    public virtual string CurrentDate { get; set; }
    [DataMember]
    public virtual string RegistrationDate { get; set; }
    [DataMember]
    public virtual string ExpirationDate { get; set; }
}

我的序列化尝试:

XmlDocument Xmldoc = new XmlDocument();
Xmldoc.Load(string.Format(url));

string xml = Xmldoc.InnerXml;
var serializer = new DataContractSerializer(typeof(License));
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
License license = (License)serializer.ReadObject(memoryStream);
memoryStream.Close();

以下元素已序列化:

  • Guid
  • ValidKey

以下元素未序列化:

  • 地址
  • 的currentdate
  • RegistrationDate
  • 到期日期

使用“blah”替换xml文件中的字符串日期也不起作用。是什么给了什么?

1 个答案:

答案 0 :(得分:5)

DataContractSerializer要求表示属性的XML元素按字母顺序排列。所以,你的XML应该是:

<?xml version="1.0" encoding="utf-8" ?> 
<License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain">
    <CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> 
    <ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> 
    <Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> 
    <RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> 
    <Url>http://www.gmail.com</Url> 
    <ValidKey>true</ValidKey> 
</License>

正如John指出的那样,例外是你在DataMember属性上使用Order属性。在这种情况下,XML元素必须按指定的顺序排列。

相关问题