我仍然会使用 XML,但只需编写您自己的序列化程序。您可以使用 .Net 中的 XML 读取器/写入器类来创建简单的 XML 格式:
<TopObject>
<SubObject>
<SubObject>
etc.
</SubObject>
<SubObject>
etc.
</SubObject>
</SubObject>
<SubObject></SubObject>
</TopObject>
我不知道你是否认为这足够人类可读,但最好是 .Net 序列化程序创建的东西。递归地读/写很容易。
示例:
这是一个您可以适应的简单示例。假设我有这个类:
public class Node {
public Node(String _SomeProperty) {
this.SomeProperty = _SomeProperty;
}
public String SomeProperty;
public List<Node> Children = new List<Node>();
}
每个Node 都有一个属性,称为SomeProperty。它也可以有孩子; Children 属性中的更多 Nodes。
这是来自控制台应用程序的main,它从此类创建一些数据以进行序列化:
static void Main(string[] args) {
// Make some data for testing
Node baseObject = new Node("This is the base class");
List<Node> Children = new List<Node>(){
new Node("This is a child"),
new Node("This is another child")
};
baseObject.Children = Children;
Node aSubChild = new Node("This is a child of a child");
baseObject.Children[0].Children = new List<Node>() { aSubChild };
// Serialize
XmlWriter writer = XmlWriter.Create("test.xml");
writer.WriteStartDocument();
RecursivelySerialize(ref writer, baseObject);
writer.Flush();
}
它调用了一个名为 RecursivelySerialize 的方法,该方法完成了实际工作:
private static void RecursivelySerialize(ref XmlWriter writer, Node sc) {
writer.WriteStartElement("Node");
writer.WriteElementString("SomeProperty", sc.SomeProperty);
if (sc.Children.Count > 0) {
writer.WriteStartElement("Nodes");
foreach (Node scChild in sc.Children)
RecursivelySerialize(ref writer, scChild);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
这种方法并不复杂。为了改进它,您可以使用反射来动态序列化任何类型的类。这是我在运行上述代码时得到的输出(格式很好):
<?xml version="1.0" encoding="utf-8"?>
<Node>
<SomeProperty>This is the base class</SomeProperty>
<Nodes>
<Node>
<SomeProperty>This is a child</SomeProperty>
<Nodes>
<Node>
<SomeProperty>This is a child of a child</SomeProperty>
</Node>
</Nodes>
</Node>
<Node>
<SomeProperty>This is another child</SomeProperty>
</Node>
</Nodes>
</Node>