]> git.tdb.fi Git - ext/subsurface.git/blob - parse.c
Turn the XML into something almost parseable.
[ext/subsurface.git] / parse.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <libxml/parser.h>
5 #include <libxml/tree.h>
6
7 static const char *nodename(xmlNode *node, char *buf, int len)
8 {
9         /* Don't print out the node name if it is "text" */
10         if (!strcmp(node->name, "text")) {
11                 node = node->parent;
12                 if (!node || !node->name)
13                         return "root";
14         }
15
16         buf += len;
17         *--buf = 0;
18         len--;
19
20         for(;;) {
21                 const char *name = node->name;
22                 int i = strlen(name);
23                 while (--i >= 0) {
24                         unsigned char c = name[i];
25                         *--buf = tolower(c);
26                         if (!--len)
27                                 return buf;
28                 }
29                 node = node->parent;
30                 if (!node || !node->name)
31                         return buf;
32                 *--buf = '.';
33                 if (!--len)
34                         return buf;
35         }
36 }
37
38 #define MAXNAME 64
39
40 static void show_one_node(xmlNode *node)
41 {
42         int len;
43         const unsigned char *content;
44         char buffer[MAXNAME];
45         const char *name;
46
47         content = node->content;
48         if (!content)
49                 return;
50
51         /* Trim whitespace at beginning */
52         while (isspace(*content))
53                 content++;
54
55         /* Trim whitespace at end */
56         len = strlen(content);
57         while (len && isspace(content[len-1]))
58                 len--;
59
60         if (!len)
61                 return;
62
63         name = nodename(node, buffer, sizeof(buffer));
64
65         printf("%s: %.*s\n", name, len, content);
66 }
67
68 static void show(xmlNode *node)
69 {
70         xmlNode *n;
71
72         for (n = node; n; n = n->next) {
73                 show_one_node(n);
74                 show(n->children);
75         }
76 }
77
78 static void parse(const char *filename)
79 {
80         xmlDoc *doc;
81
82         doc = xmlReadFile(filename, NULL, 0);
83         if (!doc) {
84                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
85                 return;
86         }
87
88         show(xmlDocGetRootElement(doc));
89         xmlFreeDoc(doc);
90         xmlCleanupParser();
91 }
92
93 int main(int argc, char **argv)
94 {
95         int i;
96
97         LIBXML_TEST_VERSION
98
99         for (i = 1; i < argc; i++)
100                 parse(argv[i]);
101         return 0;
102 }