UNPKG

1.21 kBJavaScriptView Raw
1'use strict';
2/**
3 * js2xml module
4 * @module js2xml
5 * @see module:index
6 */
7const lang = require('zero-lang');
8const xmlFormat = require('./xml-format');
9const tplComment = require('./template/comment');
10const tplNode = require('./template/node');
11const tplProcessingInstruction = require('./template/processing-instruction');
12
13function escapeQuota(attrs) {
14 lang.forIn(attrs, (value, key) => {
15 attrs[key] = value.replace(/"/g, '"');
16 });
17 return attrs;
18}
19
20function js2xml(obj) {
21 if (obj.type === 8 /* 'Comment' */) return tplComment(obj);
22 if (obj.type === 3 /* 'TextNode' */) return obj.text || '';
23 if (obj.type === 7 /* 'ProcessingInstruction' */) return tplProcessingInstruction(obj);
24 const content = lang.map(obj.children || [], (child) => js2xml(child)).join('');
25 if (obj.type === 9 /* 'Document' */) return content;
26 return tplNode(lang.extend({
27 attributes: escapeQuota(obj.attributes || {}),
28 content,
29 tag: obj.tag || '',
30 }, obj));
31}
32
33module.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};