1

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?

Aaron Hao
  • 59
  • 8

1 Answers1

2

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.

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • as you seem both @HanHao and @ paolo be new here please have a quick view at the [tour]. The comments are not the place to chat, there would be a chatroom for that. To say thank you simply upvote and/accept the good answers. This is to gain reputation for good answers and also to ensure quality here on SO. Thanks for your participation. – inetphantom Nov 13 '17 at 09:08