Tuesday, 10 September 2013

XML deserialization: All properties null / EndElement not expected

XML deserialization: All properties null / EndElement not expected

Any help is appreciated with this, I've been struggling.
From a HTTP request I receive an XML response. I have no control over its
structure, so I must match that structure with my data contracts. However,
no matter what i do, all the properties in the Result object are either
null or the default value.
XML Structure:
<Customnamedroot xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Results="2"
Skip="0">
<Object>
<Something xsi:nil="true" />
<Anything>2012-06-08T11:21:27</Anything>
<Booleanthing>true</Booleanthing>
</Object>
<Object>
<Something>1463387</Something>
<Anything>2012-06-07T09:16:11.41</Anything>
<Booleanthing>true</Booleanthing>
</Object>
</Customnamedroot>
The call:
SearchResults objects = response.Content.ReadAsAsync<SearchResults>().Result;
Corresponding Data Contract classes:
[CollectionDataContract(Name = "Customnamedroot", ItemName = "Object",
Namespace = "")]
public class SearchResults : List<Result>
{
}
//[DataContract(Name = "Object")]
public class Result
{
[DataMember(Order = 1, Name = "Something", IsRequired = false)]
public decimal? Something{ get; set; }
[DataMember(Order = 2, Name = "Anything", IsRequired = true,
EmitDefaultValue = false)]
public DateTime Anything{ get; set; }
[DataMember(Order = 3, Name = "Booleanthing", IsRequired = true,
EmitDefaultValue = false)]
public bool Booleanthing{ get; set; }
}
Edit: This problem occurs if the DataContract(Name = "Object") is omitted.
If that DataContractAttribute is added, I get the following error:
System.Runtime.Serialization.SerializationException: Error in line 1
position 157.
'EndElement' 'Object' from namespace '' is not expected.
Expecting element 'Something| Anything'.
What am I doing wrong?

No comments:

Post a Comment