c++ - 使用rapidxml循环遍历节点

标签 c++ xml rapidxml

我是在 C++ 中使用 XML 的新手,我想循环遍历 XML 节点并将 的 'id' 属性打印到 vector 中。这是我的 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]);

如何循环遍历节点?

最佳答案

将 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;
} 

关于c++ - 使用rapidxml循环遍历节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9149974/

相关文章:

具有函数指针常量数组的 C++ 模板化静态类

c++ - 实现友元函数

java - 使用 STaX 解析多个 XML 片段

c++ - 使用 RapidXML 解析 XML 文件 - 仅解析文件的第一行

c++ - RapidXML 节点异常处理

c++ - 为什么goto这个宏定义会导致程序崩溃?

c++ - OPENGL:使用 VBO 的方形类

c++ - 试图了解 RapidXml 内存分配

android - 如何在android中解析下面的xml?

xml - VB.net解析XML(属性)youtube gdata