1 |
|
2 |
|
3 |
|
4 |
|
5 | var INDENT = ' ';
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | function XMLWriter(contentWriter) {
|
13 | this.cw = contentWriter;
|
14 | this.stack = [];
|
15 | }
|
16 |
|
17 | function attrString(attrs) {
|
18 | if (!attrs) {
|
19 | return '';
|
20 | }
|
21 | var ret = [];
|
22 | Object.keys(attrs).forEach(function(k) {
|
23 | var v = attrs[k];
|
24 | ret.push(k + '="' + v + '"');
|
25 | });
|
26 | return ret.length === 0 ? '' : ' ' + ret.join(' ');
|
27 | }
|
28 |
|
29 | XMLWriter.prototype.indent = function(str) {
|
30 | return (
|
31 | this.stack
|
32 | .map(function() {
|
33 | return INDENT;
|
34 | })
|
35 | .join('') + str
|
36 | );
|
37 | };
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | XMLWriter.prototype.openTag = function(name, attrs) {
|
45 | var str = this.indent('<' + name + attrString(attrs) + '>');
|
46 | this.cw.println(str);
|
47 | this.stack.push(name);
|
48 | };
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | XMLWriter.prototype.closeTag = function(name) {
|
56 | if (this.stack.length === 0) {
|
57 | throw new Error('Attempt to close tag ' + name + ' when not opened');
|
58 | }
|
59 | var stashed = this.stack.pop(),
|
60 | str = '</' + name + '>';
|
61 |
|
62 | if (stashed !== name) {
|
63 | throw new Error(
|
64 | 'Attempt to close tag ' +
|
65 | name +
|
66 | ' when ' +
|
67 | stashed +
|
68 | ' was the one open'
|
69 | );
|
70 | }
|
71 | this.cw.println(this.indent(str));
|
72 | };
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | XMLWriter.prototype.inlineTag = function(name, attrs, content) {
|
80 | var str = '<' + name + attrString(attrs);
|
81 | if (content) {
|
82 | str += '>' + content + '</' + name + '>';
|
83 | } else {
|
84 | str += '/>';
|
85 | }
|
86 | str = this.indent(str);
|
87 | this.cw.println(str);
|
88 | };
|
89 |
|
90 |
|
91 |
|
92 | XMLWriter.prototype.closeAll = function() {
|
93 | var that = this;
|
94 | this.stack
|
95 | .slice()
|
96 | .reverse()
|
97 | .forEach(function(name) {
|
98 | that.closeTag(name);
|
99 | });
|
100 | };
|
101 |
|
102 | module.exports = XMLWriter;
|