c++rapidxml

Rapidxml traversing nodes


the xml file:

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

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

my cpp file:

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

the output expected is :

name 's value is : hanhao

age 's value is : 18

but the real output is :

name 's value is : hanhao

's value is : hanhao

age 's value is : 18

's value is : 18

's value is :

node name : name

node value : hanhao

node name : age

node value : 18

who can tell me why this problem occurs?


Solution

  • The problem is: every node has its type and you're processing every kind of node (including the comment at the end). It looks like you want to deal with node_element only, so:

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

    This should yield the expected output.