TinyXML: Save document to char * or string

荒凉一梦 提交于 2019-12-04 23:38:46

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)

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();

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();

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!