User Tools

Site Tools


wiki:nodexml

Table of Contents

XMLO

I wrote this because I needed it. It just not check for errors very well. It does not throw (you can catch right?)

But it filled a niche and it works nice and simply.

Here is an example. “xel” creates an element “xtx” creates a text node. I should, I suppose, support raw 'String's and 'string's (*sigh*).

Any object can be passed in as attributes.

'xel' calling convention is xel(name, attributes, children) or xel(name) or xel(name, children).

'children' are ALWAYS and array. 'attributes' are ALWAYS an object. 'name' is always a string.

var x = require('./xmlo.js');

var doc =
    x.xel('html', [
        x.xel('link', { 'href': 'https://fonts.googleapis.com/css?family=Raleway|Rubik+Mono+One', 'rel': 'stylesheet' }),
        x.xel('link', { 'href': '/styles/style_regular_font_2.css', 'rel': 'stylesheet'}),
        x.xel('title', [ x.xtx('this is where the title goes & it will "escape"')]),
        x.xel('body', { 'onload': 'main()' }, [
            x.xel('h1', [ x.xtx('this is the <heading!>. it\s a nice!') ])])
        ]);

console.log(doc.render());

Library Code

///(C)opyright 2017 kuiash.com code@kuiash.com

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;')
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&apos;');
}

function Xtx(txt) {
    this.txt = txt;
}

Xtx.prototype.render = function() {
    return encodeHTML(this.txt);
}

function Xel(name, p0, p1) {
    this.name = name;
    this.attributes = {};
    this.children = [];
    var children = null;
    if (p0 !== undefined) {
        if (p0 instanceof Array) {
            children = p0;
        } else if (p0 instanceof Object) {
            this.attributes = p0;
        }
        if (p1 !== undefined) {
            if (p1 instanceof Array) {
                children = p1;
            }
        }
    }
    if (children !== null) {
        this.children = children;
    }
}

Xel.prototype.render = function() {
    var out = '<' + this.name;
    if (Object.keys(this.attributes).length) {
        for(var key in this.attributes) {
            out += ' ' + key + '="' + encodeHTML(this.attributes[key]) + '"';
        }
    }
    if (this.children.length > 0) {
        out += '>';
        for(var i = 0; i < this.children.length; ++i) {
            out += this.children[i].render();
        }
        out += '</' + this.name + '>';
    } else {
        out += ' />';
    }
    return out;
}

exports.encode = function(txt) {
    return encodeHTML(txt);
}

exports.xel = function(name, p0, p1) {
    return new Xel(name, p0, p1);
}

exports.xtx = function(txt) {
    return new Xtx(txt);
}
wiki/nodexml.txt · Last modified: 2017/05/12 12:48 by xylene