Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# System.Xml.Serialization Self-nested elements

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~

like image 464
Jake Avatar asked May 22 '26 17:05

Jake


1 Answers

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

set { if(value != null) foreach(Node n in value) children.add(n) }
like image 168
csharptest.net Avatar answered May 25 '26 06:05

csharptest.net



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!