0

我基本上只想读取并打印出 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

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

4

1 回答 1

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

像这样的东西应该工作。

于 2013-07-11T21:19:50.617 回答