我正在尝试反序列化
<graph>
<node>
<node>
<node></node>
</node>
</node>
<node>
<node>
<node></node>
</node>
</node>
</graph>
与
[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) }
};
}
但它一直说对象未创建,尝试设置子节点时遇到空引用。上面有什么问题?
提前致谢〜
答案 0 :(得分:1)
我无法重现您的错误。我使用了以下代码:
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;
}
您可以发布用于反序列化的内容吗?
答案 1 :(得分:1)
你发出的是在set handler(s)中,如果不是null则添加:
set { if(value != null) foreach(Node n in value) children.add(n) }