UNPKG

1.23 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}
18
19function js2xml(obj) {
20 if (obj.type === 8 /* 'Comment' */) return tplComment(obj);
21 if (obj.type === 3 /* 'TextNode' */) return obj.text || '';
22 if (obj.type === 7 /* 'ProcessingInstruction' */) return tplProcessingInstruction(obj);
23 const content = lang.map(obj.children || [], (child) => js2xml(child)).join('');
24 if (obj.type === 9 /* 'Document' */) return content;
25 return tplNode(lang.extend({
26 attributes: escapeQuota(obj.attributes || {}),
27 content,
28 tag: obj.tag || '',
29 }, obj));
30}
31
32module.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};