【问题标题】:Looping through a node using rapidxml使用rapidxml循环一个节点
【发布时间】:2012-02-05 14:22:03
【问题描述】:

我不熟悉将 XML 与 C++ 结合使用,我想遍历 XML 节点并将 'id' 属性打印到向量中。这是我的 XML

<?xml version="1.0" encoding="UTF-8"?>
<player playerID="0">
    <frames>
        <frame id="0"></frame>
        <frame id="1"></frame>
        <frame id="2"></frame>
        <frame id="3"></frame>
        <frame id="4"></frame>
        <frame id="5"></frame>
    </frames>
</player>

这就是我加载 XML 的方式

rapidxml::xml_document<> xmlDoc;

/* "Read file into vector<char>"*/
std::vector<char> buffer((std::istreambuf_iterator<char>(xmlFile)), std::istreambuf_iterator<char>( ));
buffer.push_back('\0');
xmlDoc.parse<0>(&buffer[0]);

如何循环遍历节点?

【问题讨论】:

  • 也许是时候接受博扬的回答了?

标签: c++ xml rapidxml


【解决方案1】:

一旦你将 xml 加载到你的文档对象中,你可以使用first_node() 来获取指定的子节点(或者只是第一个);那么你可以使用next_sibling() 来遍历它的所有兄弟姐妹。使用first_attribute() 获取节点的指定(或只是第一个)属性。这是代码的样子:

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <rapidxml.hpp>
using std::cout;
using std::endl;
using std::ifstream;
using std::vector;
using std::stringstream;
using namespace rapidxml;

int main()
{
    ifstream in("test.xml");

    xml_document<> doc;
    std::vector<char> buffer((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>( ));
    buffer.push_back('\0');
    doc.parse<0>(&buffer[0]);

    vector<int> vecID;

    // get document's first node - 'player' node
    // get player's first child - 'frames' node
    // get frames' first child - first 'frame' node
    xml_node<>* nodeFrame = doc.first_node()->first_node()->first_node();

    while(nodeFrame)
    {
        stringstream ss;
        ss << nodeFrame->first_attribute("id")->value();
        int nID;
        ss >> nID;
        vecID.push_back(nID);
        nodeFrame = nodeFrame->next_sibling();
    }

    vector<int>::const_iterator it = vecID.begin();
    for(; it != vecID.end(); it++)
    {
        cout << *it << endl;
    }

    return 0;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多