1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | const lang = require('zero-lang');
|
8 | const xmlFormat = require('./xml-format');
|
9 | const tplComment = require('./template/comment');
|
10 | const tplNode = require('./template/node');
|
11 | const tplProcessingInstruction = require('./template/processing-instruction');
|
12 |
|
13 | function escapeQuota(attrs) {
|
14 | lang.forIn(attrs, (value, key) => {
|
15 | attrs[key] = value.replace(/"/g, '"');
|
16 | });
|
17 | return attrs;
|
18 | }
|
19 |
|
20 | function js2xml(obj) {
|
21 | if (obj.type === 8 ) return tplComment(obj);
|
22 | if (obj.type === 3 ) return obj.text || '';
|
23 | if (obj.type === 7 ) return tplProcessingInstruction(obj);
|
24 | const content = lang.map(obj.children || [], (child) => js2xml(child)).join('');
|
25 | if (obj.type === 9 ) return content;
|
26 | return tplNode(lang.extend({
|
27 | attributes: escapeQuota(obj.attributes || {}),
|
28 | content,
|
29 | tag: obj.tag || '',
|
30 | }, obj));
|
31 | }
|
32 |
|
33 | module.exports = (obj, options) => {
|
34 | options = options || {};
|
35 | const result = js2xml(obj);
|
36 | if (options.beautify) return xmlFormat.beautify(result, options.indent);
|
37 | return xmlFormat.uglify(result, options.preserveComments);
|
38 | };
|