使用rapidxml进行读取和打印。打印多个兄弟姐妹C ++的问题

时间:2013-07-11 21:06:43

标签: c++ xml parsing printing rapidxml

我基本上只想阅读并打印出xml文件的内容。

我的xml文件(tree_test.xml)如下所示:

<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>

我的C ++代码(在Windows上使用VS 2012)如下所示:

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;
}

我的输出:

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

我想要的输出:

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

我似乎无法获得要打印的第二本书元素。它可能与我循环的方式有关。我确信这很简单,但我已经被困了一段时间。请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您需要为每个循环更新子项,否则它们仍将指向没有兄弟姐妹的值:

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();
}

这样的事情应该有效。