-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
json2xml.js
53 lines (46 loc) · 1.19 KB
/
json2xml.js
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
'use strict';
var xmlWrite = require('./xmlWrite');
function traverse(obj,parent,attributePrefix) {
var result = [];
var array = Array.isArray(obj);
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
var propArray = Array.isArray(obj[key]);
var output = array ? parent : key;
if (typeof obj[key] !== 'object'){
if (key.indexOf(attributePrefix) === 0) {
xmlWrite.attribute(key.substring(1),obj[key]);
}
else {
xmlWrite.startElement(output);
xmlWrite.content(obj[key]);
xmlWrite.endElement(output);
}
}
else {
if (!propArray) {
xmlWrite.startElement(output);
}
traverse(obj[key],output,attributePrefix);
if (!propArray) {
xmlWrite.endElement(output);
}
}
}
return result;
}
module.exports = {
// TODO convert this to an options object
getXml : function(obj,attrPrefix,standalone,indent,indentStr,fragment) {
var attributePrefix = (attrPrefix ? attrPrefix : '@');
if (fragment) {
xmlWrite.startFragment(indent,indentStr);
}
else {
xmlWrite.startDocument('UTF-8',standalone,indent,indentStr);
}
traverse(obj,'',attributePrefix);
return xmlWrite.endDocument();
}
};