2

我是在 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('\0');
xmlDoc.parse<0>(&buffer[0]);

如何循环通过节点?

4

1 回答 1

3

将 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;
} 
于 2012-02-05T15:43:35.620 回答