C# System.Xml.Serialization Self-nested elements

青春壹個敷衍的年華 提交于 2019-12-12 08:57:02

问题


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~


回答1:


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

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



回答2:


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?



来源:https://stackoverflow.com/questions/2851454/c-sharp-system-xml-serialization-self-nested-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!