【问题标题】:Pretty print with libxml2?用 libxml2 打印漂亮吗?
【发布时间】:2019-05-29 07:16:04
【问题描述】:

使用 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

【问题讨论】:

    标签: c++ c libxml2


    【解决方案1】:

    盗自here:

    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
    

    【讨论】:

    • 该代码缺少某些内容或不太正确。 xmlDoc 是从哪里传入进行格式化的?
    • xmlDoc 在两个 sn-ps 代码之间传递;您使用 xmlDoc 写入 buf,也许 xmlNodeDump 可能会有所帮助
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 2014-08-13
    • 2016-07-07
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多