【问题标题】:Creating string with libxml2 (c++)使用 libxml2 (c++) 创建字符串
【发布时间】:2010-11-11 15:00:00
【问题描述】:

我的问题是我想创建 xml 树并获得一个简单的字符串对象(甚至是 char*)。 而且我无法将 xml 保存到文件中。

所以在输入中我有带有完整 xml 树的 xmlDocPtr,并且想要获取包含 xml 但不使用文件的字符串。

感谢关注。

【问题讨论】:

    标签: c++ libxml2


    【解决方案1】:

    使用xmlDocDumpMemory 或其任何表亲。用法:

    void xml_to_string(xmlDocPtr doc, std::string &out)
    {
        xmlChar *s;
        int size;
        xmlDocDumpMemory(doc, &s, &size);
        if (s == NULL)
            throw std::bad_alloc();
        try {
            out = (char *)s;
        } catch (...) {
            xmlFree(s);
            throw;
        }
        xmlFree(s);
    }
    

    【讨论】:

    • 谢谢你们!你真棒=)
    【解决方案2】:

    我之前写的东西。希望对您有所帮助....

    xmlDocPtr pDoc = ... // your xml docuemnt
    
    xmlCharPtr psOutput;
    int iSize;
    xmlDocDumpFormatMemoryEnc(pDoc, &psOutput, &iSize, "UTF-8", 1);
    
    // psOutput should point to the string.
    
    // Don't forget to free the memory.
    xmlFree(psOutput);
    

    【讨论】:

      【解决方案3】:

      如果您使用 xmlDocDumpMemory() 请小心。在使用 xmlDocDumpMemory() 之后,在最后调用 xmlCleanupParser()。似乎 xmlDocDumpMemory() 在内部使用它。

      【讨论】:

        【解决方案4】:

        我无法得到你想要的,但在更改节点值后,你可以使用 xmlDocDump 将其保存easily

        【讨论】:

        • OP 说他确实想将 XML 保存到文件中。
        • ups.. 我想我不能很好地解决问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-13
        • 1970-01-01
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多