summaryrefslogtreecommitdiff
path: root/misc/samples/xml_sax.c
blob: b586a21b75f526fc54fb5f66d0c6e9dd7c513f27 (plain)
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
/*
 * Simple SAX example
 */

#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

static int cb_total = 0;

/*
 * Callback implementations
 */
static void
cb_start_document(void *ctx ATTRIBUTE_UNUSED)
{
	cb_total++;
	fprintf(stdout, "SAX.startDocument()\n");
}

static void
cb_end_document(void *ctx ATTRIBUTE_UNUSED)
{
	cb_total++;
	fprintf(stdout, "SAX.endDocument()\n");
}

static void
cb_start_element(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar **atts)
{
	int i;

	cb_total++;
	fprintf(stdout, "SAX.startElement(%s", (char *) name);
	if (atts != NULL) {
		for (i = 0;(atts[i] != NULL);i++) {
			fprintf(stdout, ", %s='", atts[i++]);
			if (atts[i] != NULL)
				fprintf(stdout, "%s'", atts[i]);
		}
	}
	fprintf(stdout, ")\n");
}

static void
cb_end_element(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name)
{
	cb_total++;
	fprintf(stdout, "SAX.endElement(%s)\n", (char *) name);
}

static void
cb_characters(void *ctx ATTRIBUTE_UNUSED, const xmlChar *ch, int len)
{
	char output[40];
	int i;

	cb_total++;
	for (i = 0;(i<len) && (i < 30);i++)
		output[i] = ch[i];
	output[i] = 0;

	fprintf(stdout, "SAX.characters(%s, %d)\n", output, len);
}

static void
cb_comment(void *ctx ATTRIBUTE_UNUSED, const xmlChar *value)
{
	cb_total++;
	fprintf(stdout, "SAX.comment(%s)\n", value);
}

/*
 * Define callback struct
 */
xmlSAXHandler debugSAXHandlerStruct = {
	NULL, NULL, NULL, NULL, NULL, NULL,
	NULL, NULL, NULL, NULL, NULL, NULL,
	cb_start_document,
	cb_end_document,
	cb_start_element,
	cb_end_element,
	NULL,
	cb_characters,
	NULL, NULL,
	cb_comment,
	NULL, NULL, NULL, NULL, NULL, NULL,
	1
};
xmlSAXHandlerPtr debugSAXHandler = &debugSAXHandlerStruct;

int main(int argc, char **argv) {
	int rc;

	if (argc != 2)
		return 1;

	cb_total = 0;
	rc = xmlSAXUserParseFile(debugSAXHandler, NULL, argv[1]);
	if (rc)
		fprintf(stdout, "xmlSAXUserParseFile returned error %d\n", rc);

	fprintf(stdout, "\ncallback calls: %d\n", cb_total);

	xmlCleanupParser();
	xmlMemoryDump();

	return(0);
}