其他分享
首页 > 其他分享> > rapidxml往xml文件循环写入内容

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

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

标签:xml,node,doc,写入,allocate,rapidxml,append
来源: https://blog.csdn.net/arible/article/details/119042230