libxml2无法从缓冲区解析,但从文件中成功解析

时间:2013-07-18 20:01:29

标签: c xml-parsing libxml2

我有一个使用libxml2编写器将XML文档写入缓冲区的函数,但是当我尝试使用xmlParseMemory从内存中解析文档时,它只返回解析器错误。我也尝试将文档写入文件并使用xmlParseFile解析它并成功解析。

这是我初始化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);

doc在调用此函数后总是为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
    ^

我现在已经有一段时间无法解决这个问题了,而且我没有想法。如果有人有,我将不胜感激,如果你愿意分享它。

1 个答案:

答案 0 :(得分:5)

您正在使用sizeof来确定xml数据的大小。对于总是要返回的char指针4.您可能需要的是strlen

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