C # System.Xml.Serialization Nested Elements

I'm 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 he continues to say that the object was not created, a null reference occurs when trying to establish child nodes. What's wrong?

Thanks in advance ~

+3
source share
2 answers

You specify in the task handler, add, if not null:

set { if(value != null) foreach(Node n in value) children.add(n) }
+1
source

I can not reproduce your mistake. 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 use for deserialization?

+1
source

Source: https://habr.com/ru/post/1745843/


All Articles