C#:具有循环链接的节点的xml序列化 [英] C# : xml serialization of nodes with cyclic links

查看:129
本文介绍了C#:具有循环链接的节点的xml序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的Node类:

class Node {
    IEnumerable<Node> inputs;
}

基本上定义了一个简单的图. 我想将图形序列化为易于阅读的形式,因此通常我会说xml是可行的方法. 但是XML并不是在考虑循环依赖的情况下制作的:)

那么-对我的图进行序列化的最佳方法是什么?

我可以想到几种方法:

  • 抛弃XML,创建自己的格式.
  • 使用XML,用唯一的ID标记每个节点,将连接列表与节点分开存储,并在加载后解析

但是我认为其他人以前一定也遇到过同样的问题,因此可能会有更好的选择. 有人知道扎实的方法吗?

解决方案

对于xml,我会使用id方法(更改DTO模型,使其不是不是循环的.)

请注意, DataContractSerializer 可以通过以下方式自动支持循环对象图:在重载的构造函数中为preserveObjectReferences选项传递true;它不会像XmlSerializer输出那样简单,但是仍然可以读取.

I have a class Node something like this :

class Node {
    IEnumerable<Node> inputs;
}

Which basicly defines a simple graph. I want to serialize my graph to a human-readable form, so normally I'd say xml would be the way to go. But XML wasn't made with cyclic dependencies in mind :)

So - what would be the best way to go for serialization of my graph ?

I can think of a few ways :

  • ditch XML, create my own format.
  • use XML, tag each node with a unique ID, store connection-lists separate from the Nodes and resolve after loading

But I think other people must have had this same problem before, so there might be some better options. Does anyone know of a solid approach ?

解决方案

For xml, I would go with the id approach (changing the DTO model such that it isn't cyclic).

Note that DataContractSerializer can support cyclic object graphs automatically by passing in true for the preserveObjectReferences option in the overloaded constructors; it won't be quite as simple as XmlSerializer output, but it will still be readable.

这篇关于C#:具有循环链接的节点的xml序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆