Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating xml against relax ng in ANSI C

Tags:

c

xml

relaxng

Is it possible to validate an xml file against a Relax NG schema in ANSI C? I have come across this library called libxml2 but all help I could get from it is with respect to how to parse an xml file. Please help.

And if it can be done, what are the steps? Utterly ignorant about this w.r.t. the C environment.

like image 647
Gyandeep Avatar asked Jun 22 '11 07:06

Gyandeep


2 Answers

Here is a minimalistic example (you should of course add your own error checking):

 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/types.h>

 #include <libxml/xmlmemory.h>
 #include <libxml/parser.h>
 #include <libxml/relaxng.h>

 int
 main(int argc, char *argv[])
 {
    int status;
    xmlDoc *doc;
    xmlRelaxNGPtr schema;
    xmlRelaxNGValidCtxtPtr validctxt;
    xmlRelaxNGParserCtxtPtr rngparser;

    doc = xmlParseFile(argv[1]);

    rngparser = xmlRelaxNGNewParserCtxt(argv[2]);
    schema = xmlRelaxNGParse(rngparser);
    validctxt = xmlRelaxNGNewValidCtxt(schema);

    status = xmlRelaxNGValidateDoc(validctxt, doc);
    printf("status == %d\n", status);

    xmlRelaxNGFree(schema);
    xmlRelaxNGFreeValidCtxt(validctxt);
    xmlRelaxNGFreeParserCtxt(rngparser);
    xmlFreeDoc(doc);
    exit(EXIT_SUCCESS);
 }

Compile this with gcc -I/usr/include/libxml2 rngval.c -o rngval -lxml2

You can check the relevant documentation at http://xmlsoft.org/html/libxml-relaxng.html

like image 82
jmbr Avatar answered Oct 22 '22 04:10

jmbr


I can't quickly give a source code example to answer your question but the answers you need can be found in the source for the xmllint utility that's part of the libxml2 utility. There's a great deal of developer documentation for libxml 2 at http://xmlsoft.org/docs.html and you can browse or download the source code for xmllint from the GIT repo. Take a look at the code in the streamFile function (around line 1800)

like image 1
Nic Gibson Avatar answered Oct 22 '22 05:10

Nic Gibson