【问题标题】:libxml2 fails to parse from buffer but parses successfully from filelibxml2 无法从缓冲区解析但从文件成功解析
【发布时间】:2013-07-18 20:01:28
【问题描述】:

我有一个使用 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-&gt;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
    ^

我已经有很长一段时间无法弄清楚这一点,而且我没有想法。如果有人有的话,如果你能分享一下,我将不胜感激。

【问题讨论】:

    标签: c xml-parsing libxml2


    【解决方案1】:

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

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

    【讨论】:

    • 我忽略的最小的细节总是会导致最大的问题。感谢您指出这一点。
    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2021-03-10
    • 1970-01-01
    • 2020-11-27
    • 2021-11-13
    • 2018-11-21
    相关资源
    最近更新 更多