Skip to content
This repository was archived by the owner on Jan 7, 2021. It is now read-only.

Commit 20ecfd9

Browse files
committed
Merge pull request #64 from idy/issue-61
fix #61
2 parents a9eaeeb + 753f690 commit 20ecfd9

1 file changed

Lines changed: 40 additions & 11 deletions

File tree

lib/json2xml.js

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
module.exports = function toXml(json, xml) {
2-
var xml = xml || '';
32
if (json instanceof Buffer) {
43
json = json.toString();
54
}
@@ -14,7 +13,13 @@ module.exports = function toXml(json, xml) {
1413
} else {
1514
obj = json;
1615
}
16+
var toXml = new ToXml();
17+
toXml.parse(obj);
18+
return toXml.xml;
19+
}
1720

21+
ToXml.prototype.parse = function(obj) {
22+
var self = this;
1823
var keys = Object.keys(obj);
1924
var len = keys.length;
2025

@@ -28,10 +33,9 @@ module.exports = function toXml(json, xml) {
2833
it.forEach(function(subVal) {
2934
if (typeof(subVal) != 'object') {
3035
if (key == '$t') {
31-
xml += subVal;
36+
self.addTextContent(subVal);
3237
} else {
33-
xml = xml.replace(/>$/, '');
34-
xml += ' ' + key + '="' + subVal + '">';
38+
self.addAttr(key, subVal);
3539
}
3640
}
3741
})
@@ -49,18 +53,43 @@ module.exports = function toXml(json, xml) {
4953
var elem = elems[j];
5054

5155
if (typeof(elem) == 'object') {
52-
xml += '<' + key + '>';
53-
xml = toXml(elem, xml);
54-
xml += '</' + key + '>';
56+
self.openTag(key);
57+
self.parse(elem);
58+
self.closeTag(key);
5559
}
5660
}
5761
} else if (typeof(obj[key]) == 'object') {
58-
xml += '<' + key + '>';
59-
xml = toXml(obj[key], xml);
60-
xml += '</' + key + '>';
62+
self.openTag(key);
63+
self.parse(obj[key]);
64+
self.closeTag(key);
6165
}
6266
}
6367

64-
return xml;
6568
};
6669

70+
ToXml.prototype.openTag = function(key) {
71+
this.completeTag();
72+
this.xml += '<' + key;
73+
this.tagIncomplete = true;
74+
}
75+
ToXml.prototype.addAttr = function(key, val) {
76+
this.xml += ' ' + key + '="' + val + '"';
77+
}
78+
ToXml.prototype.addTextContent = function(text) {
79+
this.completeTag();
80+
this.xml += text;
81+
}
82+
ToXml.prototype.closeTag = function(key) {
83+
this.completeTag();
84+
this.xml += '</' + key + '>';
85+
}
86+
ToXml.prototype.completeTag = function() {
87+
if (this.tagIncomplete) {
88+
this.xml += '>';
89+
this.tagIncomplete = false;
90+
}
91+
}
92+
function ToXml() {
93+
this.xml = '';
94+
this.tagIncomplete = false;
95+
}

0 commit comments

Comments
 (0)