我是pugixml的新手。考虑我给了here XML。我想获取每个学生的NameRoll的值。下面的代码只能找到标记,而不能找到值。

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

我想要每个学生的姓名和名册的输出。如何修改以上代码?另外,如果可以引用here(按Test),我可以直接编写pugixml支持的xpath。如果是这样,我如何获得在Pugixml中使用Xpath寻找的值。

最佳答案

仅使用Xpath的方法如下:

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

关于c++ - Pugixml C++解析XML,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27844061/

10-10 18:40