2013-07-18 31 views
0

我有一個函數,它使用libxml2編寫器將XML文檔寫入緩衝區,但是當我嘗試使用xmlParseMemory從內存解析文檔時,它只返回解析器錯誤。我也嘗試將文檔寫入文件並使用xmlParseFile解析它,併成功解析。libxml2無法從緩衝區解析,但從文件解析成功

這是我如何初始化xml文檔的寫入器和緩衝區。

int rc, i = 0; 
    xmlTextWriterPtr writer; 
    xmlBufferPtr buf; 

    // Create a new XML buffer, to which the XML document will be written 
    buf = xmlBufferCreate(); 
    if (buf == NULL) 
    { 
    printf("testXmlwriterMemory: Error creating the xml buffer\n"); 
    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) 
    { 
    printf("testXmlwriterMemory: Error creating the xml writer\n"); 
    return; 
    } 

    // Start the document with the xml default for the version, 
    // encoding UTF-8 and the default for the standalone 
    // declaration. 
    rc = xmlTextWriterStartDocument(writer, NULL, ENCODING, NULL); 
    if (rc < 0) 
    { 
    printf 
    ("testXmlwriterMemory: Error at xmlTextWriterStartDocument\n"); 
    return; 
    } 

我通過XML文檔來使用 int ret = validateXML(buf->content);

這裏是validateXML的第一部分

int validateXML(char *buffer) 
{ 
xmlDocPtr doc; 
xmlSchemaPtr schema = NULL; 
xmlSchemaParserCtxtPtr ctxt; 
char *XSDFileName = XSDFILE; 
char *XMLFile = buffer; 
int ret = 1; 

doc = xmlReadMemory(XMLFile, sizeof(XMLFile), "noname.xml", NULL, 0); 

文檔總是調用此函數,這意味着後NULL另一功能進行驗證它沒有解析文件。

以下是的錯誤,運行程序返回

Entity: line 1: parser error : ParsePI: PI xm space expected 
<?xm 
    ^
Entity: line 1: parser error : ParsePI: PI xm never end ... 
<?xm 
    ^
Entity: line 1: parser error : Start tag expected, '<' not found 
<?xm 
    ^

我一直無法現在算出這個相當長的一段時間,我的想法。如果有人有任何問題,我將不勝感激,如果你會分享它。

回答

4

您正在使用sizeof來確定xml數據的大小。對於一直會返回的字符指針4.你可能需要的是strlen

doc = xmlReadMemory(XMLFile, strlen(XMLFile), "noname.xml", NULL, 0); 
+0

它總是最小的細節,我忽略了導致最大的問題。感謝您指出了這一點。 – user2516281