xref: /freebsd/contrib/expat/examples/elements.c (revision c98323078dede7579020518ec84cdcb478e5c142)
1 /* This is simple demonstration of how to use expat. This program
2    reads an XML document from standard input and writes a line with
3    the name of each element to standard output indenting child
4    elements by one tab stop more than their parent element.
5 */
6 
7 #include <stdio.h>
8 #include "expat.h"
9 
10 static void
11 startElement(void *userData, const char *name, const char **atts)
12 {
13   int i;
14   int *depthPtr = userData;
15   for (i = 0; i < *depthPtr; i++)
16     putchar('\t');
17   puts(name);
18   *depthPtr += 1;
19 }
20 
21 static void
22 endElement(void *userData, const char *name)
23 {
24   int *depthPtr = userData;
25   *depthPtr -= 1;
26 }
27 
28 int
29 main(int argc, char *argv[])
30 {
31   char buf[BUFSIZ];
32   XML_Parser parser = XML_ParserCreate(NULL);
33   int done;
34   int depth = 0;
35   XML_SetUserData(parser, &depth);
36   XML_SetElementHandler(parser, startElement, endElement);
37   do {
38     size_t len = fread(buf, 1, sizeof(buf), stdin);
39     done = len < sizeof(buf);
40     if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
41       fprintf(stderr,
42               "%s at line %d\n",
43               XML_ErrorString(XML_GetErrorCode(parser)),
44               XML_GetCurrentLineNumber(parser));
45       return 1;
46     }
47   } while (!done);
48   XML_ParserFree(parser);
49   return 0;
50 }
51