Validating xml against relax ng in ANSI C

穿精又带淫゛_ 提交于 2019-12-06 03:32:17

问题


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.


回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/6436456/validating-xml-against-relax-ng-in-ansi-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!