Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate an xml file using a schema file in C programming language using libxml2

Tags:

c

libxml2

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

like image 427
Priyanka Bhatia Avatar asked Mar 24 '26 05:03

Priyanka Bhatia


1 Answers

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 :)

like image 191
Jarekczek Avatar answered Mar 25 '26 19:03

Jarekczek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!