trying to deserialize a Xml string, but always get problem for elements like these:
<Taxable />
<DefaultPurchasePrice />
My C# code snippet:
[XmlRoot(ElementName = "Product", Namespace = "http://api.test.com/version/1", IsNullable = false)]
public class Product
{
public Guid Guid { get; set; }
public string ProductName { get; set; }
public bool Taxable { get; set; }
public Decimal DefautSellPrice { get; set; }
[XmlElement("DefaultPurchasePrice")]
public string DefaultPurchasePriceElement
{
get
{
if (DefaultPurchasePrice == null)
return String.Empty;
else
return DefaultPurchasePrice.ToString();
}
set
{
if (value == null | value.Length == 0)
DefaultPurchasePrice = null;
else
DefaultPurchasePrice = Convert.ToDecimal(value);
}
}
[XmlIgnore]
public decimal? DefaultPurchasePrice{ get; set;}
}
Seems like
xsi:nil="true"
attribute in XML should solve my problem. But as we are using XML provided by from a REST server as part of an API testing. We don't have direct control how the XML be constructed, but we can give them feedback. So I think I should explicitly ask them to fix their XML, as it is their XML's problem right?
In the mean time, I could get individual elements deserialized by the following code:
[XmlElement("DefaultPurchasePrice")]
public string DefaultPurchasePriceElement
{
get
{
if (DefaultPurchasePrice == null)
return String.Empty;
else
return DefaultPurchasePrice.ToString();
}
set
{
if (value == null | value.Length == 0)
DefaultPurchasePrice = null;
else
DefaultPurchasePrice = Convert.ToDecimal(value);
}
}
[XmlIgnore]
public decimal? DefaultPurchasePrice{ get; set;}
But there are quite a few null elements in the XML string, and again, the other party could fix their XML so I don't need do anything to my deserialize code in that case right?
Anyway, could I do something in my code before deserialization so the XML could have proper xsi:nil="true" attribute for null elements so that I don't need do much in my C# code but can quickly fix their XML?
I am thinking about @Ryan's solution in the 2nd last from here: deserialize-xml-with-empty-elements-in-c, but not sure are there any better solutions?
EDIT:
Just did a small test, adding xsi:nill='true' in XML null elements will indeed working with my existing C# code. But I do need make sure my C# class mapped from XML have nullable datattype for those null elements comeing from XML with xsi:nill='true'. But it make sense: when some datafield come from XML might be a null type, I need explicitly define the correspond datatype as nullable. I am much happy with that rather than my current solution.