-
Notifications
You must be signed in to change notification settings - Fork 6
/
xmlvalidate.c
65 lines (54 loc) · 1.95 KB
/
xmlvalidate.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xmlschemas.h>
static xmlSchemaPtr wxschemas = NULL;
static int options = XML_PARSE_COMPACT | XML_PARSE_BIG_LINES;
char *removeFinalNewline(char *str) {
if (str == NULL) return str;
int length = strlen(str);
if (str[length-1] == '\n') str[length-1] = '\0';
return str;
}
void printError(void *userData, xmlErrorPtr error) {
xmlNode *node = error->node;
char *tag = "";
if (node) tag = node->name;
char *file = error->file;
if (!file) file = "";
char *part = error->str1;
if (!part) part = "";
int line = error->line;
if (!line) line = xmlGetLineNo(node);
int column = error->int2;
if (!column) column = -1;
fprintf(stdout,
"{\"code\":%d,\"message\":\"%s\",\"level\":%d,\"node\":\"%s\","
"\"file\":\"%s\",\"line\":%d,\"column\":%d,\"part\":\"%s\"}\n",
error->code, removeFinalNewline(error->message), error->level, tag,
file, line, column, part);
}
int init(const char *schemas, int size, const char *filename) {
xmlSchemaParserCtxtPtr ctxt = xmlSchemaNewMemParserCtxt(schemas, size);
xmlSchemaSetParserStructuredErrors(ctxt, printError, NULL);
xmlSetStructuredErrorFunc(ctxt, printError);
wxschemas = xmlSchemaParse(ctxt);
if (wxschemas == NULL) fprintf(stderr, "%s failed to compile\n", filename);
xmlSchemaFreeParserCtxt(ctxt);
return (wxschemas == NULL) ? -1 : 0;
}
int validate(const xmlChar *document, const char *filename) {
if (wxschemas == NULL) {
fprintf(stderr, "No schema compiled\n");
return -1;
}
xmlSchemaValidCtxtPtr vctxt = xmlSchemaNewValidCtxt(wxschemas);
xmlSchemaSetValidStructuredErrors(vctxt, printError, NULL);
xmlSetStructuredErrorFunc(vctxt, printError);
xmlSchemaValidateSetFilename(vctxt, filename);
xmlDocPtr doc = xmlReadDoc(document, filename, NULL, options);
int ret = xmlSchemaValidateDoc(vctxt, doc);
xmlSchemaFreeValidCtxt(vctxt);
return ret;
}