我最近一直在使用Rapidxml并遇到了以下问题。当我尝试添加非硬编码但在程序运行时生成的属性时,rapidxml会插入错误的字符。
以下是我的代码示例:
void ProcessInfo::retriveInfo()
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { sizeof(pe) };
BOOL fOk = ProcessFirst( &pe, hSnapshot );
using namespace rapidxml;
xml_document<> doc;
xml_node<>* decl = doc.allocate_node(node_declaration);
decl->append_attribute(doc.allocate_attribute("version", "1.0"));
decl->append_attribute(doc.allocate_attribute("encoding", "utf-8"));
doc.append_node(decl);
xml_node<>* root = doc.allocate_node(node_element, "rootnode");
while(fOk)
{
std::string processFile = pe.szExeFile;
xml_node<>* processName = doc.allocate_node(node_element, PROCESS_NODE);
root->append_node( processName );
processName->append_attribute(doc.allocate_attribute( PROCESS_NAME, processFile.c_str() ) );
char szPID[PID_BUFFER];
memset(szPID, 0x00, sizeof(szPID) );
itoa(pe.th32ProcessID, szPID, 10 );
processName->append_attribute(doc.allocate_attribute( PROCESS_ID, szPID ));
char szParentPID[PID_BUFFER];
itoa( pe.th32ParentProcessID, szParentPID, 10 );
processName->append_attribute(doc.allocate_attribute( PROCESS_PARENT_ID, szParentPID ));
std::cout << processFile.c_str() << " " << szPID << " " << szParentPID << std::endl;
fOk = ProcessNext( &pe, hSnapshot );
}
doc.append_node( root );
std::cout << doc;
}
编码似乎有问题,但我无法理解,为什么?有人可以帮助我吗?
答案 0 :(得分:4)
当您将字符串传递给RapidXML时,它不会复制它,它只会记住该地址。因此,您添加的“变量”字符串将被覆盖,从而破坏RapidXML文档。
请阅读此部分。
http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1modifying_dom_tree
特别是,您需要更改使用如下变量的allocate_attribute调用: -
char *node_name = doc.allocate_string(szPID); // Allocate string and copy name into it
processName->append_attribute(doc.allocate_attribute(PROCESS_ID, node_name); // Set node name to node_name
我的这个问题也可能是相关的:How to fix RapidXML String ownership concerns?