问题
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.
回答1:
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)
回答2:
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();
回答3:
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();
回答4:
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.
来源:https://stackoverflow.com/questions/110393/tinyxml-save-document-to-char-or-string