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.