Given an XElement input:
<?xml version="1.0"?>
<Item Number="100" ItemName="TestName1" ItemId="1"/>
with an Item model like:
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public int? Number { get; set; }
// public DateTime? Created {get; set;}
}
Why does this code:
public static T DeserializeObject<T>(XElement element) where T : class, new()
{
try
{
var serializer = new XmlSerializer(typeof(T));
var x = (T)serializer.Deserialize(element.CreateReader());
return x;
}
catch
{
return default(T);
}
}
Returns an Item model with default values: ItemId=0, ItemName=null, Number=null instead of the correct values.
This can be fixed by adding attributes to the model [XmlAttribute("ItemName")] but I do not want to require XmlAttributes.
The addition of a nullable DateTime field to the Item model also causes a deserialization exception, even if it has an XmlAttribute.
I have the equivalent code in JSON.net where all I am doing is p.ToObject() on the JToken to deserialize it to an Item object. Is there another technique or deserializer that handles this better without having to qualify with attributes, etc. and that handles nullable values. It should be that easy for the XML version too.
Please consider this question carefully, as I had another similar question closed as [Duplicate] where none of the answers actually covered what I was asking.
It seems if you don't decorate your C# class properties with the XML attributes, the deserializer assumes the properties are elements and not attributes.
I ended up writing the custom deserializer below that is similar to the json deserializer method for jToken. It should work for basic, flat objects that have simple type properties like string, int, datetime, etc. and the nullable versions of those types. It does not require XmlAttributes.
When you know what is, you can write the following:
You can try Cinchoo ETL - an open source lib for your needs.
Hope it helps.
Disclaimer: I'm the author of this library.