views:

249

answers:

1

I have an XML file that I'm trying to serialize into an object. Some elements are being ignored.

My XML File:

<?xml version="1.0" encoding="utf-8" ?> 
<License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"&gt;
<Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> 
<Url>http://www.gmail.com&lt;/Url&gt; 
<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>

My class definition:

[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; }
}

And my Serialization attempt:

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();

The following elements are serialized:

  • Guid
  • ValidKey

The following elements are not serialized:

  • Url
  • CurrentDate
  • RegistrationDate
  • ExpirationDate

Replacing the string dates in the xml file with "blah" doesn't work either. What gives?

+3  A: 

DataContractSerializer requires the XML elements representing properties to be in alphabetical order. So, your XML should be:

<?xml version="1.0" encoding="utf-8" ?> 
<License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"&gt;
    <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&lt;/Url&gt; 
    <ValidKey>true</ValidKey> 
</License>

The exception, as John pointed out, is if you are using the Order property on your DataMember attributes. In that case, the XML elements must be in the specified order.

Aaron
@Aaron: thanks for mentioning alphabetical order. I didn't know that. I suggest you add the use of the `Order` property to your answer.
John Saunders
Hi John - to answer your initial question, I had tried rearranging them. I have used Aaron's solution and also added the Order attribute to help safeguard about someone's edit unintentially breaking it in the future. Thank you both
splatto