使用rapidxml在节点中循环

Looping through a node using rapidxml

本文关键字:循环 节点 rapidxml 使用      更新时间:2023-10-16

我刚开始在C++中使用XML,我想循环遍历一个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('');
xmlDoc.parse<0>(&buffer[0]);

如何循环通过节点?

一旦将xml加载到文档对象中,就可以使用first_node()获取指定的子节点(或仅获取第一个子节点);则可以使用CCD_ 2遍历其所有同级。使用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('');
    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;
}