微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

rapidxml往xml文件循环写入内容

初次使用rapidxml往xml文件中循环写入内容,以下是错误演示:

bool StudentMgr::save ()
{
    ///创建文件操作对象
    rapidxml::xml_document<> doc;

    myNode* root    =   doc.allocate_node(rapidxml::node_pi,doc.allocate_string("xml version='1.0' encoding='gb2312'"));
    doc.append_node(root);
    myNode* Studentinformation      =   doc.allocate_node(rapidxml::node_element,"Studentinformation",nullptr);
    myNode* StudentList             =   doc.allocate_node(rapidxml::node_element,"StudentList",nullptr);
    doc.append_node(Studentinformation);
    Studentinformation->append_node(StudentList);
    MapStudent::iterator it;

    char str[1024];
    const char* name;
    const char* sex;
    const char* id;
    const char* telnumber;
    int iter=0;

    ///取出容器内容
    for (it = _students.begin (); it != _students.end (); it++)
    {
        name          =         it->second._name.data();
        sex           =         it->second._sex.data();
        id            =         it->second._id.data();
        telnumber     =         it->second._telnumber.data();

        sprintf_s(str,"%s %s %s %s",name,sex,id,telnumber);
        StudentList->append_node(doc.allocate_node(rapidxml::node_element, "Student",str));
    }
    ///打开文件并写入xml信息
    std::string text;
	rapidxml::print(back_inserter(text), doc, 0);
    std::ofstream out(_fileName);
    out<<doc;
    return true;
}

代码中未定义的变量为类的成员变量已在容器中赋值,就不再赘述,以上代码能通过编译也能运行,本函数是想实现将容器中的成员变量循环赋值给student节点,然后重定义该xml文件内容;但真实效果却是student的每一行都为容器中最后的元素的值。

正确的代码只需要将上图代码中的

StudentList->append_node(doc.allocate_node(rapidxml::node_element, "Student",str));

修改

StudentList->append_node(doc.allocate_node(rapidxml::node_element, "Student", doc.allocate_string(str, 1024)));

其中巨细暂时还没有探究,现只解决了这个问题,希望有了解的大佬可以讲解一下,不胜感激。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。