-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjson2xml.cpp
More file actions
62 lines (55 loc) · 1.39 KB
/
json2xml.cpp
File metadata and controls
62 lines (55 loc) · 1.39 KB
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
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <json/json.h>
#include <string>
#include <iostream>
using namespace Json;
void write_value(xmlNodePtr n, Json::Value &value) {
switch (value.type()) {
case nullValue:
break;
case booleanValue:
case intValue:
case uintValue:
case realValue:
case stringValue: {
std::string v = value.asString();
xmlNodeSetContent(n, (const xmlChar*)(v.c_str()));
break;
}
case arrayValue: {
ArrayIndex size = value.size();
for (ArrayIndex index = 0; index < size; ++index) {
xmlNodePtr c = xmlNewChild(n, NULL, BAD_CAST "element", NULL);
write_value(c, value[index]);
}
break;
}
case objectValue: {
Value::Members members(value.getMemberNames());
for (auto it = members.begin(); it != members.end(); ++it) {
xmlNodePtr c = xmlNewChild(n, NULL, (const xmlChar*)it->c_str(), NULL);
write_value(c, value[*it]);
}
break;
}
}
}
xmlDocPtr parse_json(Json::Value &src) {
xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr n = xmlNewNode(NULL, BAD_CAST "root");
write_value(n, src);
xmlDocSetRootElement(doc, n);
return doc;
}
int main() {
Json::Value root;
Json::Reader reader;
reader.parse(std::cin, root);
xmlDocPtr doc = parse_json(root);
xmlChar *xmlbuff;
int buffersize;
xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 1);
printf("%s", (char *) xmlbuff);
xmlFree(xmlbuff);
}