1
votes

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>
1
Funny thing, you are trying to do opposite to this problem. Perhaps you can define Nodes as List<Node>? If you serialize list (not array), then it's by default empty event if it's missing (null) in the xml. - Sinatr
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

1 Answers

1
votes

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 ; }
    } 
}