I'm using the System.Xml.Serialization library to deserialize an XML structure containing a set of nodes. I get the value null for the array when there are no nodes, but I would like the default value to be an empty array instead. What would be the best way to achieve this? I tried to use a default value for the property, but that does not seem to work for arrays.
This is the data structure I am trying to deserialize:
public class MyData
{
[System.Xml.Serialization.XmlElement("Node")]
public Node[] Nodes { get; set; } = new Node[] {};
}
public class Node
{
public string Id { get; set; } = "DefaultId";
}
Deserializing the following XML gives me a null value in the Nodes property:
<MyData/>
Deserializing the following XML gives me an array of length one, where the element has the Id set to "DefaultId".
<MyData> <Node/> </MyData>