如何使用libxml2使用C编程语言中的模式文件validationxml文件

我一直在尝试使用我的C代码中的模式文件来validationXML文件。 validation成功说明文件是有效还是无效。

但我的问题是它只打印有效/无效。 应该有一个报告/输出关于xml文件中缺少的内容,以防它无效。 可能类似于XML文件中的行号。

希望,我已经清楚了。

这是我的C代码: –

int validateXmlFile() { int iError = 0; xmlDocPtr pDoc; xmlDocPtr pSchemaDoc; xmlSchemaParserCtxtPtr pSchemaCtxt; xmlSchemaPtr pSchema; xmlSchemaValidCtxtPtr pValidCtxt; char * xmlFilename = "C:\\Documents and Settings\\pbhatia\\Desktop\\Schema\\ipt_config.xml"; char * schemaFilename = "C:\\Documents and Settings\\pbhatia\\Desktop\\Schema\\ipt_config.xsd"; PRNT(printf("Schema file : %s \n", schemaFilename)); PRNT(printf("XML file : %s \n", xmlFilename)); pDoc = xmlReadFile(xmlFilename, NULL, XML_PARSE_NONET); if (!pDoc) return -1; pSchemaDoc = xmlReadFile(schemaFilename, NULL, XML_PARSE_NONET); if (!pSchemaDoc) return -2; pSchemaCtxt = xmlSchemaNewDocParserCtxt(pSchemaDoc); if (!pSchemaCtxt) return -3; pSchema = xmlSchemaParse(pSchemaCtxt); if (!pSchema) return -4; pValidCtxt = xmlSchemaNewValidCtxt(pSchema); if(!pValidCtxt) return -5; // Attempting to validate xml with schema xmlSchemaFreeParserCtxt(pSchemaCtxt); xmlFreeDoc(pSchemaDoc); iError = xmlSchemaValidateDoc(pValidCtxt, pDoc); if (iError == 0) PRNT(printf("Document in %s is valid \n", xmlFilename)); else PRNT(printf("Document in %s is NOT valid \n", xmlFilename)); xmlSchemaFree(pSchema); xmlFreeDoc(pDoc); return 0; } 

谢谢,Priyanka

从阅读xmllint.c源代码可以看出,您可以使用xmlSchemaSetValidErrors在上下文中设置错误和警告的回调。 在最简单的情况下,你转发fprintf ,它只会打印错误。

 xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); 

UTSL 🙂

不是你的schame部分的答案,而是你的“在哪里找到”错误的答案:

  FILE *f = fopen("/temp/xml_err.log", "a"); xmlDocPtr doc; if (f) { xmlSetGenericErrorFunc(f, NULL); } doc = xmlParseMemory(xmlstr, XMLMAXSTRSIZE); if (f) { fclose(f); }