1

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>
Øystein Kolsrud
  • 359
  • 2
  • 16
  • 2
    Funny thing, you are trying to do opposite to [this problem](http://stackoverflow.com/q/31984191/1997232). Perhaps you can define `Nodes` as `List`? If you serialize list (not array), then it's by default empty event if it's missing (`null`) in the xml. – Sinatr Aug 18 '16 at 09:28
  • Wow, thanks! I had no idea lists would behave like that. Using a list instead of an array is fine for my application. It's rather strange that the behavior differs between the two types like that though. – Øystein Kolsrud Aug 18 '16 at 10:28

1 Answers1

1

Its not a deserialization problem specifically - just create a backing private variable and alter your Getter to create a default value when required.

public class MyData
{
    private Node[] nodes = null;
    [System.Xml.Serialization.XmlElement("Node")]
    public Node[] Nodes 
    {  
        get { 
                if(nodes == null) 
                {
                    nodes = new Node[];
                }
                return nodes;
            }
        set { nodes = value ; }
    } 
}
PhillipH
  • 6,182
  • 1
  • 15
  • 25
  • Yes, I was thinking of that. Or actually I was thinking of setting the setter method to "nodes = value ?? new Node[]{}", but that would prevent me from ever setting the nodes property to null, which is not necessarily what I want. I only want the deserialization to default to a non-null value. – Øystein Kolsrud Aug 18 '16 at 09:19