tags:

views:

2648

answers:

6

I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk.

It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this?

Edit: The printing & streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content.

Edit: Printing is cool.

A: 

Don't quite get what you are saying; your question is not clear. I'm guessing you are wanting to load a file into memory so that you can pass it to the document parse function. In that case, the following code should work.

#include <stdio.h>

The following code reads a file into memory and stores it in a buffer

FILE* fd = fopen("filename.xml", "rb"); // Read-only mode
int fsize = fseek(fd, 0, SEEK_END); // Get file size
rewind(fd);
char* buffer = (char*)calloc(fsize + 1, sizeof(char));
fread(buffer, fsize, 1, fd);
fclose(fd);

The file is now in the variable "buffer" and can be passed to whatever function required you to provide a char* buffer of the file to it.

SemiColon
Sorry I wasn't clear, edited.I already am using the parse function, the problem is saving the document back to a char pointer after it has been loaded.
foobar
+2  A: 

I'm not familiar with TinyXML, but from the documentation it seems that by using operator << to a C++ stream (so you can use C++ string streams) or a TiXMLPrinter class you can get an STL string with the without using a file. See TinyXML documentation (look for the "Printing" section)

gnobal
A: 

TinyXML by the moment does not implements read/write STREAM operations, only can work with files

in the documentation (where are detailed info about loadfile method) you can read "stream operations will be implemented in the future..."

I have decided to use temporaly file for work with tinyXML but for sure there are easy trick to work with stream "hack" that tinyxml see as file

regards

+1  A: 

A simple and elegant solution in TinyXml for printing a TiXmlDocument to a std::string.

I have made this little example

// Create a TiXmlDocument
TiXmlDocument *pDoc =new TiXmlDocument("my_doc_name");

// Add some content to the document, you might fill in something else ;-)
TiXmlComment* comment = new TiXmlComment("hello world" );
pDoc->LinkEndChild( comment );

// Declare a printer
TiXmlPrinter printer;

// attach it to the document you want to convert in to a std::string
pDoc->Accept(&printer);

// Create a std::string and copy your document data in to the string
std::string str = printer.CStr();

+2  A: 

Here's some sample code I am using, adapted from the TiXMLPrinter documentation:

TiXmlDocument doc;
// populate document here ...

TiXmlPrinter printer;
printer.SetIndent( "    " );

doc.Accept( &printer );
std::string xmltext = printer.CStr();
Alex B