TinyXML:将文档保存到char *或者字符串

时间:2020-03-06 14:30:06  来源:igfitidea点击:

我试图使用TinyXML从内存中读取和保存,而不是仅读取文件并将其保存到磁盘。

似乎文档的parse函数可以加载char *。但是之后,我需要将文档保存到char *中。有人知道吗?

编辑:打印和流功能不是我想要的。它们以可见格式输出,我需要实际的xml内容。

编辑:打印很酷。

解决方案

不太明白你在说什么;问题不清楚。我猜想我们想将文件加载到内存中,以便可以将其传递给文档解析功能。在这种情况下,以下代码应该起作用。

#include <stdio.h>

以下代码将文件读入内存并将其存储在缓冲区中

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

该文件现在位于变量" buffer"中,并且可以传递给我们需要为其提供文件char *缓冲区的任何函数。

我对TinyXML并不熟悉,但是从文档看来,通过对C ++流(这样我们就可以使用C ++字符串流)或者TiXMLPrinter类使用运算符<<来获得STL字符串,而无需使用文件。请参阅TinyXML文档(查找"打印"部分)

TinyXml中的一种简单优雅的解决方案,用于将TiXmlDocument打印到std :: string。

我做了这个小例子

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

这是我正在使用的一些示例代码,这些代码改编自TiXMLPrinter文档:

TiXmlDocument doc;
// populate document here ...

TiXmlPrinter printer;
printer.SetIndent( "    " );

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