rapidxml使用

string 被rapidxml截断

string str = "<Person><Name>test</Name><ID>2</ID><Name>police</Name></Person>";

    xml_document<> doc;
    doc.parse<0>( const_cast<char*>(str.c_str()) );

执行上面一段代码,没有任何问题。但若再次使用str时就会发现被rapidxml截断了,大家可以加断点看一下。

rapidxml添加属性的内存分配问题
今天在用rapidxml生成xml的时候碰到了一个奇怪的问题

rapidxml::xml_node<>* srvnode = doc.allocate_node(rapidxml::node_element,iter->m_name.c_str(),"");  
srvnode->append_attribute(doc.allocate_attribute("ip",iter->m_ip.c_str()));  
srvnode->append_attribute(doc.allocate_attribute("ftpport",toString(iter->m_ftpport).c_str()));  

生成的xml,其他地方都正常,就“ftpport”的属性总是显示乱码,开始以为是toString函数的问题,但是我换了一种转换方式后这个问题依然存在,同时我调试的时候看到的toString
的返回值也正常,最后和同时讨论后,他给我解释rapidxml的函数在创建新节点或者属性的时候,传入的参数要么是由内部分配器分配的内存要么应该指向一块短期内不会被释放的内存。
原来如此,于是我改了代码之后

rapidxml::xml_node<>* srvnode = doc.allocate_node(rapidxml::node_element,iter->m_name.c_str(),"");  
srvnode->append_attribute(doc.allocate_attribute("ip",iter->m_ip.c_str()));  

char* port = doc.allocate_string(toString(iter->m_ftpport).c_str());  
srvnode->append_attribute(doc.allocate_attribute("ftpport",port));

乱码的问题果然消失了,原来allocate_attribute方法创建一个属性的时候,attribute的m_value指针只是简单的指向了一块内存地址,在后期将doc写入文件,会将attribute转化为字符串,如果此时m_value指向的地址内存被释放的话,那么就会出现我先的问题了。所以我的解决方案就是用rapidxml自己的内存池分配一块内存,保存m_value指向的值,这样就OK了。

写在这里纯粹是做个记录,希望对某些同志也有帮助!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章