Skip to content

Commit dddf7d1

Browse files
committed
extract xml formatting
1 parent 306e78c commit dddf7d1

File tree

1 file changed

+33
-12
lines changed

1 file changed

+33
-12
lines changed

lib/xml.js

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ function xml (input, indent) {
99

1010
if (input && input.forEach) {
1111
input.forEach(function(value){
12-
output.push(resolve(value, indent, indent ? 1 : 0));
12+
output.push(format(resolve(value, indent, indent ? 1 : 0)));
1313
});
1414
} else {
15-
output.push(resolve(input, indent, indent ? 1 : 0));
15+
output.push(format(resolve(input, indent, indent ? 1 : 0)));
1616
}
1717
return output.join(indent ? '\n' : '');
1818
}
@@ -81,16 +81,37 @@ function resolve(data, indent, indent_count) {
8181

8282
}
8383

84-
return indent_spaces
85-
+ (name ? '<' + name : '')
86-
+ (attributes.length ? ' '
87-
+ attributes.join(' ')
88-
: '')
89-
+ (content.length ? (name ? '>' : '')
90-
+ content.join(indent ? '\n' : '')
91-
+ (content.length > 1 ? indent_spaces : '')
92-
+ (name ? '</' + name + '>' : '')
93-
: (name ? '/>' : ''));
84+
return { name: name,
85+
attributes: attributes,
86+
content: content,
87+
indents: indent_spaces,
88+
indent: indent };
89+
}
90+
91+
function format(elem) {
92+
if (typeof elem != 'object')
93+
return elem;
94+
95+
var len = elem.content.length;
96+
var output = elem.indents
97+
+ (elem.name ? '<' + elem.name : '')
98+
+ (elem.attributes.length ? ' ' + elem.attributes.join(' ') : '')
99+
+ (len ? (elem.name ? '>' : '') : (elem.name ? '/>' : ''));
100+
101+
if (!len)
102+
return output;
103+
104+
var first = true;
105+
while (elem.content.length) {
106+
var value = elem.content.shift();
107+
if (value === undefined)
108+
continue;
109+
output += (elem.indent && !first ? '\n' : '') + format(value);
110+
first = false;
111+
}
112+
113+
return output + (len > 1 ? elem.indents : '')
114+
+ (elem.name ? '</' + elem.name + '>' : '');
94115
}
95116

96117
function attribute(key, value) {

0 commit comments

Comments
 (0)