这与我之前的一个问题有关。我正在尝试从 xml 文件构建一棵树。我计划浏览 xml 文件并从数据中创建对象,并按前序和中序创建对象的向量,以便我可以构造树对象。我使用的 xml 文件比这要密集得多(大约 23 级左右),但这里是一个布局示例:
<?xml version="1.0" encoding="utf-8"?>
<MyJournal>
<species>
<name>Sea Creature</name>
<species>
<name>Fish</name>
<species>
<name>swordfish</name>
</species>
<species>
<name>grouper</name>
</species>
</species>
<species>
<name>Mammal</name>
<species>
<name>dolphin</name>
</species>
<species>
<name>whale</name>
</species>
</species>
</species>
<species>
<name>Land animal</name>
<species>
<name>Mammal</name>
<species>
<name>dog</name>
</species>
<species>
<name>cat</name>
</species>
</species>
<species>
<name>Bird</name>
<species>
<name>blue jay</name>
</species>
<species>
<name>robin</name>
</species>
</species>
</species>
</MyJournal>
我的预购和后购方法。首先传入根节点“MyJournal”。
void preOrder(xml_node<> *species) // add to left node
{
Node t1 = *new Node();
xml_node<> * name_node = species->first_node("name");
//If there is a value for name, set the name of the node to this name
if(name_node != 0)
{
t1.setName(name_node->value());
cout << t1.getName() << " ";
}
//If there is no name node, print the default name which is "ROOT"
if(name_node == 0)
{
cout << t1.getName() << " ";
}
for (xml_node<> * child_node = species->first_node("species"); child_node; child_node = child_node->next_sibling())
{
loop2(child_node); // add these to right node
}
}
void postOrder(xml_node<> *species) // add to left node
{
Node t1 = *new Node();
for (xml_node<> * child_node = species->first_node("species"); child_node; child_node = child_node->next_sibling())
{
loop3(child_node); // add these to right node
}
xml_node<> * name_node = species->first_node("name");
if(name_node != 0)
{
t1.setName(name_node->value());
cout << t1.getName() << " ";
}
if(name_node == 0)
{
cout << t1.getName() << " ";
}
}
到目前为止,我能够通过文件并按前序和后序获取对象,但我无法弄清楚如何按顺序获取数据,因为没有左或右指针来递归调用函数。谁能给我一些关于如何去做的指导?是否可以通过这种方式获取数据并成功构建树形结构?感谢您的任何帮助!