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
From reading
xmllint.csource code it turns out that you may setup callbacks for errors and warnings in the context, usingxmlSchemaSetValidErrors. In simplest case you forwardfprintfand it would simply print errors.UTSL 🙂