Domanda

I've been using Rapidxml lately and have faced following problem. When I try to add attributes, which are not hardcoded, but generated during program runtime rapidxml inserts wrong characters.

Here is my sample of code:

   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;   

}

It seems like something wrong with encoding, but I cannot figure it out, why? Can someone please help me?

È stato utile?

Soluzione

When you pass a string to RapidXML, it doesn't copy it, it just remembers the address. So the 'variable' strings you add will get overwritten, hence corrupting the RapidXML document.

Read this section here.

http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1modifying_dom_tree

In particular, you need to change the allocate_attribute calls that use variables like this:-

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

This question of mine may be relevant, too: How to fix RapidXML String ownership concerns?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top