Reputation: 97
I have been trying to validate XML file using schema file in my C Code. The validation happens successfully stating whether the file is valid or invalid.
But my issue is it prints valid/invalid only. There should be a report/output as to what was missing in the xml file in case it was invalid. May be something like the line number in XML file.
Hope, i have made my self clear.
Here's my C code:-
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;
}
Thanks, Priyanka
Upvotes: 3
Views: 3289
Reputation: 7866
From reading xmllint.c
source code it turns out that you may setup callbacks for errors and warnings in the context, using xmlSchemaSetValidErrors
. In simplest case you forward fprintf
and it would simply print errors.
xmlSchemaSetValidErrors(ctxt,
(xmlSchemaValidityErrorFunc) fprintf,
(xmlSchemaValidityWarningFunc) fprintf,
stderr);
UTSL :)
Upvotes: 1
Reputation: 6070
not an answer to your schame part, but an answer to your "where to find" the error:
FILE *f = fopen("/temp/xml_err.log", "a");
xmlDocPtr doc;
if (f) {
xmlSetGenericErrorFunc(f, NULL);
}
doc = xmlParseMemory(xmlstr, XMLMAXSTRSIZE);
if (f) {
fclose(f);
}
Upvotes: 0