-
Notifications
You must be signed in to change notification settings - Fork 1
/
xml2json.c
558 lines (455 loc) · 16.2 KB
/
xml2json.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/* xml2json
*
* Copyright (c) 2018 Partha Susarla <[email protected]>
*/
#define LIBXML_SCHEMAS_ENABLED
#include "cstring.h"
#include "htable.h"
#include "json.h"
#include "util.h"
#include "parsexsd.h"
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <getopt.h>
#include <libxml/parser.h>
#include <libxml/chvalid.h>
#include <libxml/xpath.h>
#include <libxml/xmlschemastypes.h>
#include <libxml/schemasInternals.h>
/**
* Hashtable
*/
enum xml_entry_type {
ENTRY_TYPE_NULL,
ENTRY_TYPE_BOOL,
ENTRY_TYPE_STRING,
ENTRY_TYPE_NUMBER,
ENTRY_TYPE_ARRAY,
ENTRY_TYPE_OBJECT,
};
struct xml_htable {
struct htable table;
};
struct xml_htable_entry {
struct htable_entry entry;
enum xml_entry_type type;
char *key;
size_t keylen;
void *value;
};
/* Global variable not prefered, need to find the correct function to pass - for now developing functionality */
static struct xml_htable_entry *alloc_xml_htable_entry(char *key,
size_t keylen,
void *value,
enum xml_entry_type type)
{
struct xml_htable_entry *e;
e = xmalloc(sizeof(struct xml_htable_entry));
e->key = xcalloc(1, keylen);
memcpy(e->key, key, keylen);
e->keylen = keylen;
e->value = value;
e->type = type;
return e;
}
static void free_xml_htable_entry(struct xml_htable_entry **e)
{
if (e && *e) {
free((*e)->key);
(*e)->key = NULL;
(*e)->keylen = 0;
if ((*e)->type == ENTRY_TYPE_STRING) {
free((*e)->value);
}
(*e)->value = NULL;
free(*e);
*e = NULL;
}
}
static int xml_htable_entry_cmpfn(const void *unused1 _unused_,
const void *entry1,
const void *entry2,
const void *unused2 _unused_)
{
const struct xml_htable_entry *e1 = entry1;
const struct xml_htable_entry *e2 = entry2;
return memcmp_raw(e1->key, e1->keylen, e2->key, e2->keylen);
}
static void xml_htable_init(struct xml_htable *ht)
{
htable_init(&ht->table, xml_htable_entry_cmpfn, NULL, 0);
}
static void *xml_htable_get(struct xml_htable *ht, char *key,
size_t keylen)
{
struct xml_htable_entry k;
struct xml_htable_entry *e;
if (!ht->table.size)
xml_htable_init(ht);
htable_entry_init(&k, bufhash(key, keylen));
k.key = key;
k.keylen = keylen;
e = htable_get(&ht->table, &k, NULL);
return e ? e : NULL;
}
static void xml_htable_put(struct xml_htable *ht,
char *key,
size_t keylen, void *value,
enum xml_entry_type type)
{
struct xml_htable_entry *e;
if (!ht->table.size)
xml_htable_init(ht);
e = alloc_xml_htable_entry(key, keylen, value, type);
htable_entry_init(e, bufhash(key, keylen));
htable_put(&ht->table, e);
}
static void *xml_htable_remove(struct xml_htable *ht, char *key,
size_t keylen)
{
struct xml_htable_entry e;
if (!ht->table.size)
xml_htable_init(ht);
htable_entry_init(&e, bufhash(key, keylen));
return htable_remove(&ht->table, &e, key);
}
static void xml_htable_free(struct xml_htable *ht)
{
struct htable_iter iter;
struct xml_htable_entry *e;
htable_iter_init(&ht->table, &iter);
while ((e = htable_iter_next(&iter))) {
free_xml_htable_entry(&e);
}
htable_free(&ht->table, 0);
}
/**
* XML parsing
*/
static void *parse_xmlnode(xmlNodePtr node, enum xml_entry_type *type);
static void *parse_xml_element_attributes(xmlAttrPtr attr, void *attrobj,
enum xml_entry_type *type)
{
if (attr == NULL) {
*type = ENTRY_TYPE_NULL;
return NULL;
}
if (attrobj == NULL)
attrobj = json_new();
while (attr != NULL) {
cstring str;
void *val;
/* Append '@' to the attribute name */
cstring_init(&str, 0);
cstring_addch(&str, '@');
cstring_addstr(&str, (char *)attr->name);
val = parse_xmlnode(attr->children, type);
if (*type == ENTRY_TYPE_STRING) {
JsonObject *strobj;
strobj = json_string_obj(val);
free(val);
json_prepend_member(attrobj, str.buf, strobj);
} else {
printf("attributes: non string type entry!\n");
}
attr = attr->next;
cstring_release(&str);
}
*type = ENTRY_TYPE_OBJECT;
return attrobj;
}
static int parse_xml_element_node(xmlNodePtr node, struct xml_htable *ht,
enum xml_entry_type *type)
{
void *val = NULL;
int has_attr = 0;
void *attrval = NULL;
JsonObject *attrobj = NULL;
if (node == NULL) {
*type = ENTRY_TYPE_NULL;
return -1;
}
val = parse_xmlnode(node->children, type);
switch (*type) {
case ENTRY_TYPE_NULL:
xfree(val);
val = NULL;
break;
case ENTRY_TYPE_STRING:
if (node->properties) {
attrobj = json_new();
json_prepend_member(attrobj, "#text",
json_string_obj(val));
free(val);
val = attrobj;
}
break;
case ENTRY_TYPE_OBJECT:
case ENTRY_TYPE_ARRAY:
case ENTRY_TYPE_BOOL:
case ENTRY_TYPE_NUMBER:
default:
break;
}
if (node->properties != NULL) {
/* We need to parse XML attributes */
attrval = parse_xml_element_attributes(node->properties, val,
type);
if (val == NULL)
val = attrval;
has_attr = 1;
}
xml_htable_put(ht, (char *)node->name, xmlStrlen(node->name),
val, *type);
return has_attr;
}
static char *parse_xml_text_node(xmlNodePtr node, enum xml_entry_type *type,
size_t *slen)
{
xmlChar *content;
cstring str;
size_t len = 0, i = 0;
if (node->content == NULL)
return NULL;
cstring_init(&str, 0);
content = xmlNodeGetContent(node);
len = xmlStrlen(content);
for (i = 0; i < len; i++) {
if ((content[i] == 0x20) ||
((0x9 <= content[i]) && (content[i] <= 0xa)) ||
(content[i] == 0xd) ||
(content[i] == '\r') ||
(content[i] == '\n') ||
(content[i] == 0x0a)) {
continue;
}
cstring_addch(&str, content[i]);
}
if (!content) *type = ENTRY_TYPE_NULL;
xmlFree(content);
if (str.len == 0) {
*type = ENTRY_TYPE_NULL;
cstring_release(&str);
} else {
*type = ENTRY_TYPE_STRING;
}
return cstring_detach(&str, slen);
}
static JsonObject *xml_htable_to_json_obj(struct xml_htable *ht)
{
JsonObject *jobj = NULL;
struct htable_iter iter;
struct xml_htable_entry *e = NULL;
jobj = json_new();
htable_iter_init_ordered(&ht->table, &iter);
while ((e = htable_iter_next_ordered(&iter))) {
if (e->entry.count > 1) { /* Array */
JsonObject *array = NULL;
struct xml_htable_entry *temp = NULL;
temp = e;
array = json_array_obj();
if (e->type == ENTRY_TYPE_NULL)
json_prepend_to_array(array, json_null_obj());
else if (e->type == ENTRY_TYPE_STRING)
json_prepend_to_array(array,
json_string_obj(e->value));
else
json_prepend_to_array(array, e->value);
/* Parse the other entries for the same key */
while ((temp = htable_get_next(&ht->table, temp))) {
if (temp->type == ENTRY_TYPE_NULL)
json_prepend_to_array(array,
json_null_obj());
else if (temp->type == ENTRY_TYPE_STRING)
json_prepend_to_array(array,
json_string_obj(temp->value));
else
json_prepend_to_array(array, temp->value);
}
json_append_member(jobj, (char *)e->key, array);
} else { /* Normal(?) non-array object */
if (e->type == ENTRY_TYPE_NULL)
json_append_member(jobj, e->key,
json_null_obj());
else if (e->type == ENTRY_TYPE_STRING)
json_append_member(jobj, e->key,
json_string_obj(e->value));
else
json_append_member(jobj, e->key, e->value);
}
}
return jobj;
}
static void *parse_xmlnode(xmlNodePtr node, enum xml_entry_type *type)
{
struct xml_htable ht;
xmlNodePtr n;
JsonObject *jobj;
if (node == NULL) {
*type = ENTRY_TYPE_NULL;
return NULL;
}
/* Initialise a ordered hash table */
xml_htable_init(&ht);
for (n = node; n; n = n->next) {
void *val;
size_t slen = 0;
switch(n->type) {
case XML_ELEMENT_NODE:
parse_xml_element_node(n, &ht, type);
break;
case XML_TEXT_NODE:
val = parse_xml_text_node(n, type, &slen);
if (slen == 0) continue;
xml_htable_free(&ht);
return val;
default:
break;
}
}
/* If we've got here, we are returning a json object */
*type = ENTRY_TYPE_OBJECT;
jobj = xml_htable_to_json_obj(&ht);
/* Free the ordered hash table */
xml_htable_free(&ht);
memset(&ht, 0, sizeof(struct xml_htable));
return jobj;
}
static void parse_xml_tree(xmlDocPtr doc, xmlNodePtr xsdrootin)
{
enum xml_entry_type type;
if (doc == NULL)
return;
if ((doc->type == XML_DOCUMENT_NODE) && (doc->children != NULL)) {
void *data;
char *json_str = NULL;
data = parse_xmlnode(doc->children, &type);
/* Encode our json object into a string */
json_str = json_encode((JsonObject *)data);
printf("%s\n", json_str);
xfree(json_str);
json_free(data);
data = NULL;
}
}
static void usage_and_die(void)
{
fprintf(stderr, "xml2json - A program to convert an XML file to JSON!\n");
fprintf(stderr, "USAGE: xml2json <xmlfile> -x=<xsdfile>\n");
fprintf(stderr, " xsd|x : use the xsd file to validate!\n");
fprintf(stderr, " (This is optional)\n");
fprintf(stderr, " help|h : print this help and exit!\n");
fprintf(stderr, "\n");
exit(1);
}
int main(int argc, char **argv)
{
int fd;
struct stat sbinfo;
xmlDocPtr doc = NULL;
char *base;
int xml_options = XML_PARSE_COMPACT;
xmlNodePtr xsdroot = NULL;
/* XSD related variables */
int ret ;
xmlSchemaPtr schema = NULL;
xmlSchemaParserCtxtPtr ctxt;
xmlSchemaValidCtxtPtr vctxt;
xmlParserCtxtPtr pctxt = NULL;
static struct option long_options[] = {
{"xsd", required_argument, NULL, 'x'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
int option;
int option_index;
char *xsdfile = NULL;
char *xmlfile = NULL;
#ifdef LINUX
xml_options |= XML_PARSE_BIG_LINES;
#endif
while ((option = getopt_long(argc, argv, "hx:",
long_options,
&option_index)) != -1) {
switch (option) {
case 'x':
xsdfile = optarg;
break;
case 'h':
case '?':
default:
usage_and_die();
break;
}
}
if (argc - optind != 1) {
usage_and_die();
}
xmlfile = argv[optind++];
/* mmap the file() */
if (stat(xmlfile, &sbinfo) < 0) {
perror("stat: ");
exit(EXIT_FAILURE);
}
if ((fd = open(xmlfile, O_RDONLY)) < 0) {
perror("open: ");
exit(EXIT_FAILURE);
}
base = mmap(NULL, sbinfo.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (base == (void *) MAP_FAILED){
close(fd);
perror("mmap: ");
exit(EXIT_FAILURE);
}
/* Read into an xmlDocPtr */
doc = xmlReadMemory((char *) base, sbinfo.st_size, xmlfile,
NULL, xml_options);
munmap((char *)base, sbinfo.st_size);
close(fd);
/* Read the xsd and validate the xml before building XSD and XML/JSON
structures */
if (xsdfile != NULL) {
if ((fd = open(xmlfile, O_RDONLY)) < 0) {
perror("open: ");
exit(EXIT_FAILURE);
} else {
close(fd);
}
ctxt = xmlSchemaNewParserCtxt(xsdfile);
xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc)fprintf,
(xmlSchemaValidityWarningFunc)fprintf,
stderr);
schema = xmlSchemaParse(ctxt);
if(schema == NULL) {
exit(EXIT_FAILURE);
}
xsdroot = schema->doc->children;
vctxt = xmlSchemaNewValidCtxt(schema);
pctxt = xmlSchemaValidCtxtGetParserCtxt(vctxt) ;
xmlSchemaSetValidErrors(vctxt, (xmlSchemaValidityErrorFunc)fprintf,
(xmlSchemaValidityWarningFunc) fprintf,
stderr);
ret = xmlSchemaValidateDoc(vctxt, doc);
if (ret == 0) {
printf("%s validates\n", xmlfile);
} else if (ret > 0) {
printf("%s fails to validate\n", xmlfile);
} else {
printf("%s validation generated an internal error\n", xmlfile);
}
}
if(xsdroot != NULL) {
walkXsdSchema(xsdroot);
print_array_elements();
xsdschemafree();
}
parse_xml_tree(doc, xsdfile ? xsdroot : NULL);
xmlFreeDoc(doc);
exit(EXIT_SUCCESS);
}