Wednesday, 9 July 2014

XMLSerializer: How to add null values?



I use a XMLSerializer to serialize any given Object from my database. At the moment I work with link and a dbml, so I don't use a class / model for every object, I use what is given with the dbml when you drag and drop the table from the server view into the dbml window.


This is my code to serialize this to xml:



public static string SerializeObject(object obj)
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
return xmlDoc.InnerXml;
}
}


and



public string GetCommissionByID(string id)
{
using (CommissionCalculationDataContext dc = new CommissionCalculationDataContext())
{
Commission c = (from a in dc.Commissions where a.CommissionId.Value.ToString() == id select a).First();
return Business.Helper.ObjectToXMLHelper.SerializeObject(c);
}
}


So it works like charm but in fact null values will be cuted out, so I don't see the field "lastTime" in the output xml... how to include null values as null or empty string?


No comments:

Post a Comment