Suppose we need the following XML format,
1230098-ASU-DRED T E S T Final Arizona State University 686699454647 1230098-PSY-GREY T E S T Final Arizona State University 686699454649 Now the serialization classes will look like this, [XmlRoot("ProductData")] public class INVSSTDOCP { [XmlElement("Item")] public ProductParam[] Parameters { get; set; } } [XmlRoot("Item")] public class ProductParam { public Key Key { get; set; } public string Description { get; set; } public string LongDesc { get; set; } public string AlternateKey1 { get; set; } }
For Description, LongDesc, AlternateKey1 we can directly assign the value by creating an object of ProductParam class. But for Key tag we have to create another class as this tag have subtag (StockCode). So for Key tag the class will look like,
[XmlRoot("Key")] public class Key { public string StockCode { get; set; } public Key(string stockCode) { StockCode = stockCode; } }
So for assigning value in StockCode all we have to do is to create an instance of Key class and pass our value in constructor. So following code is our desired way of getting the above xml pattern.
List param = new List(); foreach (ProdCreationENetData dbItem in lstENetDBData) { param.Add(new ProductParam { Description = dbItem.Description, LongDesc = dbItem.LongDesc, AlternateKey1 = dbItem.AlternateKey1, Key = new Key(dbItem.StockCode) } } INVSSTDOCP parent = new INVSSTDOCP(); parent.Parameters = param.ToArray();
But, when we try to serialize this class using ,
XmlSerializer serialize = new XmlSerializer(typeof(INVSSTDOCP)); serialize.Serialize(fs, parent, xmlNamespace); // fs -> FileStream object, xmlNamespace -> XmlSerializerNamespaces object.
An exception will be occurred,
XmlSerializer – There was an error reflecting type
———————————————————————————————————————————————————————–
The reason behind that every serialized class must have a default constructor. When you do not define a constructor, a default construcor will be automatically added. Here we are using our own parameterized constructor and it overrides the default constructor. This was causing the error.
So the solution will be to add a default constructor to Key class. As follows,
public Key() { StockCode = String.Empty; }
So the bottom line is,
Serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that’s fine, but if you have a constructor with a parameter, you’ll need to add the default one too.