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
|
/*
* XML to SQL converter
* Author: ryo@repack.top
* Website: https://repack.top/~ryo
* Version: alpha
*/
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define astrtr(s) s[strlen(s)-1] = '\0'
#define astrcmp(s1, s2) xmlStrcmp(s1, (xmlChar *)s2) == 0
#define asprintf(dst, ...) sprintf(dst+strlen(dst), __VA_ARGS__)
void query_create(xmlNode *root, char query[]);
void query_insert(xmlNode *root, char query[]);
int main(int argc, char *argv[])
{
xmlDocPtr doc;
xmlNodePtr root;
char *query = malloc(2048 * sizeof(char));
if (argc < 2) {
fprintf(stderr, "no file specified\n");
return 1;
}
doc = xmlReadFile(argv[1], NULL, XML_PARSE_NOBLANKS);
if (doc == NULL) {
fprintf(stderr, "can not parse the document\n");
return 1;
}
root = xmlDocGetRootElement(doc);
query_create(root, query);
query_insert(root, query);
puts(query);
xmlFreeDoc(doc);
free(query);
return 0;
}
void query_create(xmlNode *root, char *query)
{
xmlNode *cur, *parent;
int uuid = 0, end, nested = 0;
cur = root;
while (cur) {
asprintf(query, "CREATE TABLE %s(", cur->name);
cur = cur->children;
if (cur->children->type == XML_ELEMENT_NODE) {
parent = cur->parent;
nested = 1;
cur = cur->children;
}
while (cur->children->type == XML_TEXT_NODE) {
if (astrcmp(cur->name, "uuid"))
uuid = 1;
asprintf(query, "%s,", cur->name);
cur = cur->next;
if (cur == NULL) break;
}
if (nested) {
cur = parent->next;
nested = 0;
}
if (!uuid) {
asprintf(query, "%s_uuid,", root->name);
}
astrtr(query);
strcat(query, ");\n");
}
}
void query_insert(xmlNode *root, char *query)
{
xmlNode *cur, *parent;
int uuid = 0, end, nested = 0;
cur = root;
while (cur) {
asprintf(query, "INSERT INTO %s VALUES(", cur->name);
cur = cur->children;
if (cur->children->type == XML_ELEMENT_NODE) {
parent = cur->parent;
nested = 1;
cur = cur->children;
}
while (cur->children->type == XML_TEXT_NODE) {
if (astrcmp(cur->name, "uuid"))
uuid = 1;
asprintf(query, "'%s',", xmlNodeGetContent(cur));
if (cur->next == NULL) {
if (nested) {
if (cur->parent == parent->last) {
break;
}
else {
astrtr(query);
strcat(query, "),\n(");
cur = cur->parent->next->children;
}
} else {
cur = cur->next;
break;
}
} else
cur = cur->next;
}
if (nested) {
cur = parent->next;
nested = 0;
}
if (!uuid) {
asprintf(query, "'%s',", xmlNodeGetContent(root->children));
}
astrtr(query);
strcat(query, ");\n");
}
astrtr(query);
}
|