6

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.

Gyandeep
  • 63
  • 2

2 Answers2

7

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

jmbr
  • 3,298
  • 23
  • 23
  • Jmbr, Thank you so, so, so much. I am going to try this out right now. Thanks a bunch. – Gyandeep Jun 23 '11 at 06:32
  • My doubt, in addition to this, is how do I read a pre-existing Relax ng schema and an xml file as well? I mean, how do I take these two as inputs - I already have the files with me - the xml and the schema file. – Gyandeep Jun 23 '11 at 06:35
  • I'm not sure if this is what you mean but you could run the program I posted with two command line arguments as ./rngval file.xml rngschema.xml After that, the variable status should equal zero if file.xml is valid with regard to rngschema.xml. Hope this helps. – jmbr Jun 23 '11 at 07:20
  • Exactly. Got it, got it. Thanks again. Was a bit confused. – Gyandeep Jun 23 '11 at 07:31
1

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)

Nic Gibson
  • 7,051
  • 4
  • 31
  • 40