Permalink
Browse files

Merge pull request #36 from o-nix/master

toXml() fails on a specific XML structure
  • Loading branch information...
2 parents 2e047ee + 29b9b18 commit 976a158d3b87578ede7e37788a00f609838a4bb9 @c4milo c4milo committed Mar 8, 2013
Showing with 21 additions and 11 deletions.
  1. +21 −11 lib/json2xml.js
View
32 lib/json2xml.js
@@ -20,14 +20,20 @@ module.exports = function toXml(json, xml) {
// First pass, extract strings only
for (var i = 0; i < len; i++) {
- var key = keys[i];
- if (typeof(obj[key]) == 'string') {
- if (key == '$t') {
- xml += obj[key];
- } else {
- xml = xml.replace(/>$/, '');
- xml += ' ' + key + '="' + obj[key] + '">';
- }
+ var key = keys[i], value = obj[key], isArray = Array.isArray(value);
+ if (typeof(obj[key]) == 'string' || isArray) {
+ var it = isArray ? value : [value];
+
+ it.forEach(function(subVal) {
+ if (typeof(subVal) != 'object') {
+ if (key == '$t') {
+ xml += subVal;
+ } else {
+ xml = xml.replace(/>$/, '');
+ xml += ' ' + key + '="' + subVal + '">';
+ }
+ }
+ })
}
}
@@ -39,9 +45,13 @@ module.exports = function toXml(json, xml) {
var elems = obj[key];
var l = elems.length;
for (var j = 0; j < l; j++) {
- xml += '<' + key + '>';
- xml = toXml(elems[j], xml);
- xml += '</' + key + '>';
+ var elem = elems[j];
+
+ if (typeof(elem) == 'object') {
+ xml += '<' + key + '>';
+ xml = toXml(elem, xml);
+ xml += '</' + key + '>';
+ }
}
} else if (typeof(obj[key]) == 'object') {
xml += '<' + key + '>';

0 comments on commit 976a158

Please sign in to comment.