我正在尝试按照C# 中的 Tree 数据结构实现以下树结构类
delegate void TreeVisitor<T>(T nodeData);
class NTree<T>
{
T data;
LinkedList<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new LinkedList<NTree<T>>();
}
public void addChild(T data)
{
children.AddFirst(new NTree<T>(data));
}
public NTree<T> getChild(int i)
{
foreach (NTree<T> n in children)
if (--i == 0) return n;
return null;
}
public NTree<T> getChild( T data )
{
foreach (NTree<T> n in children)
{
if (n.data.Equals(data))
{
return n;
}
}
return null;
}
public void traverse(NTree<T> node, TreeVisitor<T> visitor)
{
visitor(node.data);
foreach (NTree<T> kid in node.children)
traverse(kid, visitor);
}
}
然后我想将对象的实例输出为 XML,但是我正在努力保持子/父层次结构到位
到目前为止我有
NTree<string> root = new NTree<string>( "Electronic" );
root.addChild( "Techno" );
root.getChild( "Techno" ).addChild( "Detroit" );
root.getChild( "Techno" ).addChild( "Gabba" );
root.addChild( "House" );
root.getChild( "House" ).addChild( "Deep" );
root.getChild( "House" ).addChild( "Ambient" );
root.getChild( "House" ).addChild( "Chicago" );
XElement treeAsXml = new XElement("Root");
root.traverse( root, new TreeVisitor<string>( this.ConvertNodeToXml ) );
private void ConvertNodeToXml( string nodeData )
{
XElement node = new XElement( "Node" );
node.Value = nodeData;
this.treeAsXml.Add( node );
}
这只是给了我:
<Root><Node>Electronic</Node><Node>House</Node><Node>Chicago</Node><Node>Ambient</Node><Node>Deep</Node><Node>Techno</Node><Node>Gabba</Node><Node>Detroit</Node></Root>
我怎样才能正确输出这个,理想情况如下
<Node value="Electronic">
<Node value="Techno">
<Node value="Detroit" />
<Node value="Gabba" />
</Node>
<Node value="House">
<Node value="Deep" />
<Node value="Ambient" />
<Node value="Chicago" />
</Node>
</Node>