For a project for my c++ class, I am supposed to parse and xml file and build a binary tree from it. The file is much more dense than this but the layout is as follows:
<?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>
I'm having a hard time figuring out how to parse this data so that I can build a tree. I was thinking I could use recursion for each branch but I can only get it to get one child. Someone hinted at using a queue to put the data into a tree structure, but I'm not quite sure how I could go through all the levels of the tree using a queue. I feel like recursion is the easiest way to parse the data for each branch, but I just can't figure out how to properly implement a recursive method. Here is the method I tried using. I passed in the root node first:
void loop(xml_node<> *species)
{
Node t1 = *new Node();
xml_node<> * name_node = species->first_node("name");
if(name_node != 0)
{
t1.setName(name_node->value());
cout << name_node->value() << endl;
}
xml_node<> * child = species->first_node("species");
if(child != 0)
{
cout << child->first_node("name")->value() << endl;
if(child->first_node()->next_sibling() != 0)
{
loop(child->first_node()->next_sibling());
xml_node<> * child2 = child->next_sibling();
cout << child2->first_node()->value() << endl;
loop(child2->first_node()->next_sibling());
}
}
}
It only goes through the first child of each node returning Sea Creature Fish swordfish Land animal Mammal dog
I would really appreciate any pointers in the right direction. Thanks!