Re: [xml] xmlReadMemory : error "Extra content at the end of the document"


First of all, please always state your platform and libxml2 version
when asking for help. Also provide a complete standalone code example
of your problem.

2008/11/13 Andrew Hartley <andrew hartley bcs org uk>:

I have written a DLL with a large (size = 1318109 chars) XML stored as a
resource.  I read the XML into a std::string and load it with a call to

xmlDocPtr pXmlDoc = xmlReadMemory(sXml, sXml.length(), "xml", NULL, 0);

This will never work. libxml2 is C not C++ and the API only works with
NULL terminated sequences of UTF-8 bytes, not STL strings.

This works fine in Debug mode.  But when I switch to Release mode I get NULL
returned and the error text is "Extra content at the end of the document".

I have tried parsing the std::string content into a char*, and setting the
argv[3] to "UTF-8":

            int nLen = (int)sXml.size();
       char* pszContent        = new char[nLen +2];

       strcpy_s(pszContent, nLen +2, sXml.c_str());
       pszContent[nLen]                = '\n';
       pszContent[nLen +1]     = '\0';

       xmlDocPtr pXmlDoc = xmlReadMemory(pszContent, nLen, "xml", "UTF-8", 0);

       delete[] pszContent;
       pszContent = NULL;

But I still get the same error!

Your example works here (libxml2 on GNU/Linux):

#include <string.h>
#include <libxml/parser.h>
#include <iostream>

int main (int argc, char *argv[])

    std::string sXml("<foo/>");
    int nLen = (int)sXml.size();
    char* pszContent = new char[nLen + 2];

    strncpy(pszContent, sXml.c_str(), nLen + 2);
    pszContent[nLen] = '\n';
    pszContent[nLen + 1] = '\0';

    xmlDocPtr pXmlDoc = xmlReadMemory(pszContent, nLen, "xml", "UTF-8", 0);
    if (pXmlDoc == NULL)

    delete[] pszContent;
    pszContent = NULL;



[astan franz ~]$ g++ -o test `xml2-config --libs --cflags` test.cpp
[astan franz ~]$ ./test
[astan franz ~]$ echo $?
[astan franz ~]$

Though the reason you are adding an extra newline after the XML eludes
me at the moment. Note that I had to use strncpy instead of strcpy_s,
as I'm on GNU/Linux where strcpy_s doesn't exist.


I have not resorted to attemting to debug through LibXml2 yet, and would
appreciate any advice.
View this message in context:
Sent from the Gnome - Lib - Xml - General mailing list archive at

xml mailing list, project page
xml gnome org

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]