Search code examples
c++xmlmemory-managementrapidxml

Add number (double/float) as attribute to RapidXML node


I'm pretty new to RapidXML. I want to construct an Xml document and print it to a file. Everything works but I'm not sure if I'm doing one part of the process right:

Adding an attribute to a node that is a double.

I'm using std c++ stuff:

double value = 1.0;
std::ostringstream strs;
strs << value ;
std::string str = strs.str();
char* numBuff =  doc.allocate_string(str.c_str());
xml_attribute<> *attr = doc.allocate_attribute("name",numBuff);
nodeRef->append_attribute(attr);

Is there a more elegnat/faster way? Something like (wishfull thinking):

double value = 1.0;
char* numBuff =  doc.allocate_string_from_value(value);
xml_attribute<> *attr = doc.allocate_attribute("name",numBuff);

I need to save tons of doubles into my xml file so performance is my key concern here.

Greetings, Oliver


Solution

  • I know that's an old topic, but don't have a conclusive answer. To convert values with more efficient function, prefer the old C sintax (printf), over the C++ streaming, that's more efficient. I implemented by this way:

    declare the function for conversion...

    char* double2char(double value) {
        char tmpval[64];
        sprintf(tmpval,"%f",value);
        return doc->allocate_string(tmpval);
    }
    

    ... use in the code ...

    double value = 1.0;
    xml_attribute<> *attr = doc.allocate_attribute("name",double2char(value));
    

    ... That's my implementation,maybe not the best, but a little more elegant and faster...

    Best Regards.

    ps. Sorry for my the brazilian english.