我有一个使用 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
^
我已经有一段时间无法弄清楚这一点,而且我没有想法。如果有人有的话,如果你能分享它,我将不胜感激。