Blame doc/examples/parse2.c

Packit 423ecb
/**
Packit 423ecb
 * section: Parsing
Packit 423ecb
 * synopsis: Parse and validate an XML file to a tree and free the result
Packit 423ecb
 * purpose: Create a parser context for an XML file, then parse and validate
Packit 423ecb
 *          the file, creating a tree, check the validation result
Packit 423ecb
 *          and xmlFreeDoc() to free the resulting tree.
Packit 423ecb
 * usage: parse2 test2.xml
Packit 423ecb
 * test: parse2 test2.xml
Packit 423ecb
 * author: Daniel Veillard
Packit 423ecb
 * copy: see Copyright for the status of this software.
Packit 423ecb
 */
Packit 423ecb
Packit 423ecb
#include <stdio.h>
Packit 423ecb
#include <libxml/parser.h>
Packit 423ecb
#include <libxml/tree.h>
Packit 423ecb
Packit 423ecb
/**
Packit 423ecb
 * exampleFunc:
Packit 423ecb
 * @filename: a filename or an URL
Packit 423ecb
 *
Packit 423ecb
 * Parse and validate the resource and free the resulting tree
Packit 423ecb
 */
Packit 423ecb
static void
Packit 423ecb
exampleFunc(const char *filename) {
Packit 423ecb
    xmlParserCtxtPtr ctxt; /* the parser context */
Packit 423ecb
    xmlDocPtr doc; /* the resulting document tree */
Packit 423ecb
Packit 423ecb
    /* create a parser context */
Packit 423ecb
    ctxt = xmlNewParserCtxt();
Packit 423ecb
    if (ctxt == NULL) {
Packit 423ecb
        fprintf(stderr, "Failed to allocate parser context\n");
Packit 423ecb
	return;
Packit 423ecb
    }
Packit 423ecb
    /* parse the file, activating the DTD validation option */
Packit 423ecb
    doc = xmlCtxtReadFile(ctxt, filename, NULL, XML_PARSE_DTDVALID);
Packit 423ecb
    /* check if parsing suceeded */
Packit 423ecb
    if (doc == NULL) {
Packit 423ecb
        fprintf(stderr, "Failed to parse %s\n", filename);
Packit 423ecb
    } else {
Packit 423ecb
	/* check if validation suceeded */
Packit 423ecb
        if (ctxt->valid == 0)
Packit 423ecb
	    fprintf(stderr, "Failed to validate %s\n", filename);
Packit 423ecb
	/* free up the resulting document */
Packit 423ecb
	xmlFreeDoc(doc);
Packit 423ecb
    }
Packit 423ecb
    /* free up the parser context */
Packit 423ecb
    xmlFreeParserCtxt(ctxt);
Packit 423ecb
}
Packit 423ecb
Packit 423ecb
int main(int argc, char **argv) {
Packit 423ecb
    if (argc != 2)
Packit 423ecb
        return(1);
Packit 423ecb
Packit 423ecb
    /*
Packit 423ecb
     * this initialize the library and check potential ABI mismatches
Packit 423ecb
     * between the version it was compiled for and the actual shared
Packit 423ecb
     * library used.
Packit 423ecb
     */
Packit 423ecb
    LIBXML_TEST_VERSION
Packit 423ecb
Packit 423ecb
    exampleFunc(argv[1]);
Packit 423ecb
Packit 423ecb
    /*
Packit 423ecb
     * Cleanup function for the XML library.
Packit 423ecb
     */
Packit 423ecb
    xmlCleanupParser();
Packit 423ecb
    /*
Packit 423ecb
     * this is to debug memory for regression tests
Packit 423ecb
     */
Packit 423ecb
    xmlMemoryDump();
Packit 423ecb
    return(0);
Packit 423ecb
}