0

I basically just want to read and print out the contents of an xml file.

My xml file (tree_test.xml) looks like this:

<catalog>

<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>

<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
</book>

</catalog>

My C++ Code (using VS 2012 on Windows) looks like this:

using namespace rapidxml;

int main(){
xml_document<> doc;
std::ifstream theFile ("tree_test.xml");
std::vector<char> buffer((std::istreambuf_iterator<char>(theFile)), std::istreambuf_iterator<char>());
buffer.push_back('\0');
doc.parse<0>(&buffer[0]);

xml_node<> *node = doc.first_node();
xml_node<> *child = node->first_node();
xml_node<> *child2 = child->first_node();

while(node != 0) {
    cout << node->name() << endl; 
    while (child != 0){
        cout << child->name() << " " << child->value() << endl;
        while (child2 != 0){
            cout << child2->name() << " " << child2->value() << endl;
            child2 = child2->next_sibling();
        }
     child = child->next_sibling();
     }
     node = node->next_sibling();
}
system("pause");
return EXIT_SUCCESS;
}

My Output:

catalog
book
author Gambardella, Matthew
title XML Developer's Guide
price 44.95
book

My desired output:

catalog
book
author Gambardella, Matthew
title XML Developer's Guide
price 44.95
book
author Ralls, Kim
title Midnight Rain
price 5.95

I just can't seem to get the second book elements to print. It probably has something to do with the way I'm looping. I'm sure it's something simple, but I have been stuck for a while. Please help. Thanks in advance.

Ty Roderick
  • 51
  • 2
  • 3

1 Answers1

1

You need to update the children for each loop, otherwise they will still point to the values that have no siblings left:

while(node != 0) {
    cout << node->name() << endl; 
    child = node->first_node();

    while (child != 0){
        cout << child->name() << " " << child->value() << endl;
        child2 = child->first_node();
        while (child2 != 0){
            cout << child2->name() << " " << child2->value() << endl;
            child2 = child2->next_sibling();
        }
        child = child->next_sibling();
     }
     node = node->next_sibling();
}

Something like this should work.

tfoo
  • 326
  • 2
  • 11