c++ - 使用rapidxml读取和打印。打印多个 sibling C++ 的问题

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

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

最佳答案

你需要为每个循环更新 child ,否则他们仍然会指向没有 sibling 的值:

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

这样的事情应该可行。

关于c++ - 使用rapidxml读取和打印。打印多个 sibling C++ 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17603528/

相关文章:

c++ - 自定义异常处理无法在 Ubuntu 中运行,但 Dev C 可以

xml - 使用 XML 数据的 R 中的“externalptr”错误

java - 使用占位符创建自定义注释?

ruby - 解析日期如 1240915075

python - 从电子邮件地址检索域名

c++ - 在单人纸牌游戏中移动语义

C++ 最早可以表现出来的未定义行为是什么?

c++ - vs 2010 : sqlstatementhandle and connection error 中的 mysql 和 c++

ios - 在 IOS 上使用 SOAP

json - Groovy使用匿名数组将json转换为xml失败