漂亮的打印与libxml2

Pretty print with libxml2?

本文关键字:libxml2 打印 漂亮      更新时间:2023-10-16

Using libxml2. 我可以使用 xmlSaveFormatFileEnc() 漂亮地将 XML 打印到文件中。 但是有没有办法在文本字符串或流中做同样的事情?

我想避免将 XML 写出到文件中并读回它只是为了获得 XML 的漂亮打印版本。

为了记录在案,我现在正在做的是以下内容:

xmlInitParser();
xmlKeepBlanksDefault(0);
xmlLineNumbersDefault(1);
xmlThrDefIndentTreeOutput(1);
xmlThrDefTreeIndentString("    ");
std::string content = "....."; // do something here to get the XML
xmlDoc * doc = xmlParseDoc((xmlChar*)content.c_str());
xmlSaveFormatFileEnc("output.xml", doc, "utf-8", 1); // pretty print

从这里被盗:

xmlBufferPtr buf;
/* Create a new XML buffer, to which the XML document will be
 * written */
buf = xmlBufferCreate();
if (buf == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml buffer" << std::endl;
    return;
}
/* Create a new XmlWriter for memory, with no compression.
 * Remark: there is no compression for this kind of xmlTextWriter */
writer = xmlNewTextWriterMemory(buf, 0);
if (writer == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml writer" << std::endl;
    return;
}

然后,在写入缓冲区后:

std::cout << buf->content << std::endl

只需使用 xmlSaveFormatFileTo(( 而不是 xmlSaveFormatFileEnc((https://gnome.pages.gitlab.gnome.org/libxml2/devhelp/libxml2-tree.html#xmlSaveFormatFileTo

mlBuffer *buffer = xmlBufferCreate();
xmlOutputBuffer *outputBuffer = xmlOutputBufferCreateBuffer(buffer, NULL);
xmlSaveFormatFileTo(outputBuffer, doc, "utf-8", 1);
/* pretty print output in buffer->content */
xmlBufferFree(buffer);
/* outputBuffer has been closed in xmlSaveFormatFileTo */

其他答案中显示的示例沿着正确的路径前进,但遗漏了一些重要的上下文。

实际上,您可以使用 Sabrina Jewson 显示的示例将 xml 数据生成为字符串,而无需将其写入文件系统。

在使用缓冲区的内容之前,需要确保停止写入文档。

请考虑以下示例代码:

xmlTextWriterPtr writer = NULL;
xmlBufferPtr writer_output = NULL;
std::string encodingVersion = "ISO-8859-1";
// init writer and output pointers.
writer_output = xmlBufferCreate();
writer = xmlNewTextWriterMemory(writer_output, 0);
if(writer == NULL){
    return 1;
}
// start writing document directly in memory
if(xmlTextWriterStartDocument(writer, NULL, encodingVersion.c_str(), NULL) < 0){
    return 1;
}
// Write your xml data
if(xmlTextWriterStartElement(writer, (const xmlChar*)"root") < 0){
    return 1;
}
/* other elements and attributes */
if(xmlTextWriterEndElement(writer) < 0){
    return 1;
}
// Stop writing document
if(xmlTextWriterEndDocument(writer) < 0){
    return 1;
}
if(writer != NULL)
    xmlFreeTextWriter(writer);
// You can now use the output buffer
printf("XML File : n%sn", (const char *)writer_output->content);
// free the output buffer
xmlBufferFree(writer_output);

这将允许您写入缓冲区,然后您可以根据需要将其转换为std::string