14

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.

foobar
  • 779
  • 3
  • 10
  • 18

4 Answers4

22

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
  • 24,678
  • 14
  • 64
  • 87
15

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();
Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103
  • If you're creating the character string for internal use, call printer.SetStreamPrinting() to omit indentation and line feed. – Pierre Jan 09 '21 at 21:57
10

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 without using a file. See TinyXML documentation (look for the "Printing" section)

gnobal
  • 18,309
  • 4
  • 30
  • 35
0

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
  • 2,117
  • 2
  • 14
  • 13
  • 1
    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 Sep 21 '08 at 07:01