views:

176

answers:

2

Hi, I am trying to deserialize

<graph>
<node>
   <node>
     <node></node>
   </node>
</node>
<node>
   <node>
     <node></node>
   </node>
</node>
</graph>

with

[XmlRoot("graph")]
class graph
{
   List<Node> _children = new List<node>();

   [XmlElement("node")]
   public Node[] node
   {
      get { return _children.ToArray(); }
      set { foreach(Node n in value) children.add(n) }
   };
}

class Node
{
   List<Node> _children = new List<node>();

   [XmlElement("node")]
   public Node[] node
   {
      get { return _children.ToArray(); }
      set { foreach(Node n in value) children.add(n) }
   };
}

but it keeps saying object not created, null reference encountered when trying to set children nodes. What is wrong above?

Thanks in advance~

A: 

I can't reproduce your error. I used the following code:

string xml = @"<graph>
<node>
   <node>
     <node></node>
   </node>
</node>
<node>
   <node>
     <node></node>
   </node>
</node>
</graph>";

[XmlRoot("graph")]
public class graph
{
    [XmlElement("node")]
    public Node[] node;
}

public class Node
{
    [XmlElement("node")]
    public Node[] children;
}

XmlSerializer serializer = new XmlSerializer(typeof(graph));

using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
    writer.Write(xml.Replace(Environment.NewLine, String.Empty));
    writer.Flush();
    stream.Position = 0;

    var graph = serializer.Deserialize(stream) as graph;
}

Can you post what you're using to deserialize?

Yuriy Faktorovich
Hi Yuriy, I also have no problems when using typed arrays i.e. Node[] children. The problem only occurs when using List<Node> children in the setter of the serialized property.
Jake
A: 

You issue is in the set handler(s), add if not null:

set { if(value != null) foreach(Node n in value) children.add(n) }
csharptest.net
Thanks, Indeed it solved the problem. =) but can I know why would the serializer would send in null values for a property but not for a public typed member array
Jake