Search code examples
c++xmlpugixml

Pugixml C++ parsing XML


I am a newbie in pugixml. Consider I have XML given here. I want to get value of Name and Roll of Every Student. The code below only find the tag but not the value.

#include <iostream>
#include "pugixml.hpp"

int main()
{
    std::string xml_mesg = "<data> \
    <student>\
       <Name>student 1</Name>\
       <Roll>111</Roll>\
    </student>\
    <student>\
        <Name>student 2</Name>\
        <Roll>222</Roll>\
    </student>\
    <student>\
        <Name>student 3</Name>\
        <Roll>333</Roll>\
    </student>\
</data>";
    pugi::xml_document doc;
    doc.load_string(xml_mesg.c_str());
    pugi::xml_node data = doc.child("data");
    for(pugi::xml_node_iterator it=data.begin(); it!=data.end(); ++it)
    {
        for(pugi::xml_node_iterator itt=it->begin(); itt!=it->end(); ++itt)
            std::cout << itt->name() << " " << std::endl;
    }
    return 0;
}

I want the output of Name and Roll for each student. How can I modify above code? Also, if one can refer here(press Test), I can directly write xpath which is supported by pugixml. If so, how can I get the values I seek using Xpath in Pugixml.


Solution

  • Thanks @Cornstalks for the insight of using xpath in pugixml. I used child_value given here. The code of mine was thus:

        for(pugi::xml_node_iterator it=data.begin(); it!=data.end(); ++it)
        {
            for(pugi::xml_node_iterator itt=it->begin(); itt!=it->end(); ++itt)
                std::cout << itt->name() << " " << itt->child_value() << " " << std::endl;
        }
    

    I could also use xpath as @Cornstalks suggested thus making my code as:

    pugi::xml_document doc;
    doc.load_string(xml_mesg.c_str());
    pugi::xpath_query student_query("/data/student");
    
    pugi::xpath_query name_query("Name/text()");
    pugi::xpath_query roll_query("Roll/text()");
    
    pugi::xpath_node_set xpath_students = doc.select_nodes(student_query);
    for (pugi::xpath_node xpath_student : xpath_students)
    {
        // Since Xpath results can be nodes or attributes, you must explicitly get
        // the node out with .node()
        pugi::xml_node student = xpath_student.node();
    
        pugi::xml_node name = student.select_node(name_query).node();
        pugi::xml_node roll = student.select_node(roll_query).node();
    
        std::cout << "Student name: " << name.value() << std::endl;
        std::cout << "        roll: " << roll.value() << std::endl;
    }