【问题标题】:Rapidxml traversing nodesRapidxml遍历节点
【发布时间】:2025-12-03 20:15:02
【问题描述】:

xml 文件:

<top>
    <name>hanhao</name>
    <age>18</age>
<!--
    node name : name
    node value : hanhao

    node name : age
    node value : 18
-->
</top>

我的 cpp 文件:

#include<iostream>
#include"rapidxml/rapidxml.hpp"
#include"rapidxml/rapidxml_print.hpp"
#include"rapidxml/rapidxml_utils.hpp"
using namespace std;
using namespace rapidxml;
void handlenode(xml_node<> *node){
    for(node = node -> first_node(); node != NULL; node = node -> next_sibling()){
        cout<<node -> name() <<" 's value is : "<<node->value() <<endl;
        handlenode(node);
    }
}
int main(){
    char xmldoc[] = "demo.xml";
    file<> file(xmldoc);
    xml_document<> doc;
    doc.parse<parse_comment_nodes>(file.data());
    xml_node<> *node = doc.first_node();
    handlenode(node);
    doc.allocate_node(node_element,"",node->value());
    return 0;
}

预期的输出是:

name的值为:hanhao

age 的值为:18

但真正的输出是:

name的值为:hanhao

的值为:hanhao

age 的值为:18

的值为:18

的值为:

节点名称:名称

节点值:hanhao

节点名称:年龄

节点值:18

谁能告诉我为什么会出现这个问题?

【问题讨论】:

    标签: c++ rapidxml


    【解决方案1】:

    问题是:每个节点都有自己的类型,而您正在处理每种类型的节点(包括末尾的注释)。 看起来您只想处理 node_element,所以:

    void handlenode(xml_node<> *node){
        for(node = node -> first_node(); node != NULL; node = node -> next_sibling()){
    
          if(node->type() == node_element) //chek node type
          {
            cout<<node -> name() <<" 's value is : "<<node->value() <<   endl;
            handlenode(node);
          }
        }
    }
    

    这应该会产生预期的输出。

    【讨论】:

    • 您似乎@HanHao 和@paolo 都是新来的,请在tour 快速查看。 cmets不是聊天的地方,会有一个聊天室。要说谢谢,只需赞成和/接受好的答案。这是为了获得良好答案的声誉,同时也是为了确保 SO 的质量。感谢您的参与。