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 | }
|
18 |
|
19 | function js2xml(obj) {
|
20 | if (obj.type === 8 ) return tplComment(obj);
|
21 | if (obj.type === 3 ) return obj.text || '';
|
22 | if (obj.type === 7 ) return tplProcessingInstruction(obj);
|
23 | const content = lang.map(obj.children || [], (child) => js2xml(child)).join('');
|
24 | if (obj.type === 9 ) return content;
|
25 | return tplNode(lang.extend({
|
26 | attributes: escapeQuota(obj.attributes || {}),
|
27 | content,
|
28 | tag: obj.tag || '',
|
29 | }, obj));
|
30 | }
|
31 |
|
32 | module.exports = (obj, options) => {
|
33 | options = options || {};
|
34 | const result = js2xml(obj);
|
35 | if (options.beautify) return xmlFormat.beautify(result, options.indent);
|
36 | return xmlFormat.uglify(result, options.preserveComments);
|
37 | };
|