/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Xmlify (c) Chris Veness 2014 / MIT Licence */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 'use strict'; // xmldom for createElement, createTextNode, appendChild, setAttribute; // inflection for singularisation const DomParser = require('xmldom').DOMParser; const inflection = require( 'inflection' ); /* * Summary of method: * * jsToXml(jsObj, elementName, xmlNode): * * - if elementName is attribute (& jsObj is primitive): * - add jsObj value as attribute to xmlNode * * - if jsObj is primitive: * - add xml child node 'elementName' to xmlNode * - add primitive value to xml child node * * - if jsObj is date: * - add xml child node 'elementName' to xmlNode * - add formatted date to xml child node * * - if jsObj is array: * - if wrapped-arrays & element name is plural, add xml child node 'elementName' to xmlNode * - for each element of array: * - invoke jsToXml with array element, singularised elementName, xml child node * * - if jsObj is object: * - add xml child node 'elementName' to xmlNode * - for each property of object: * - invoke jsToXml with property value, property name, xml child node */ /** * Converts JavaScript object to XML. * * @param {Object} jsObject JavaScript object to be converted to XML * @param {string} [root] Name of root XML element * @param {Object} [options] Options which can be set * @returns {string} jsObject converted into XML */ const xmlify = function(jsObject /*, [root], [options] */) { const config = { attributeChar: '_', // attributes indicator (empty string for no attributes) dateFormat: 'ISO', // how dates should be formatted (ISO / SQL / JS) xmlDeclaration: true, // whether to include an xml declaration root: 'root', // name of XML root element wrapArrays: true, // whether to wrap (plural) arrays in enclosing element }; // options: string argument specifies root, object literal specifies any option(s) for (let arg=1; arg1 && propertyName.slice(0, 1)==config.attributeChar; } /** * Dates can be formatted as ISO, SQL (space replacing 'T'), or JavaScript default format. */ function dateFormatted(date) { let d = null; if (date.toString() == 'Invalid Date') return ''; // eg MySQL 0000-00-00 try { switch (config.dateFormat) { case 'ISO': // YYYY-MM-DDTHH:MM:SS.mmmZ d = date.toISOString(); break; case 'SQL': // YYYY-MM-DD HH:MM:SS d = date.toISOString().replace('T', ' ').split('.')[0]; break; case 'JS': // JavaScript date format d = date.toString(); break; default: throw new Error('Xmlify: Unknown date format '+config.dateFormat); } } catch (e) { throw new Error('Xmlify: Invalid date '+date); } return d; } }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ module.exports = xmlify;