Created
November 12, 2014 11:24
-
-
Save ThomasWeinert/5dec25c9176918701393 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var XMLCreatorFactory = function(dom, resolver) { | |
if (dom === true) { | |
dom = document.implementation.createDocument('', '', null); | |
} else if (!(dom instanceof Document)) { | |
dom = document; | |
} | |
var lookupNamespaceURI; | |
if (resolver instanceof Function && !resolver.lookupNamespaceURI instanceof Function) { | |
lookupNamespaceURI = resolver; | |
} else if (resolver && resolver.lookupNamespaceURI instanceof Function) { | |
lookupNamespaceURI = resolver.lookupNamespaceURI; | |
} else { | |
lookupNamespaceURI = function(namespaces) { | |
namespaces = (namespaces instanceof Object) ? namespaces : {}; | |
return function(prefix) { | |
if (prefix == '') { | |
return null; | |
} | |
return namespaces[prefix] || null; | |
}; | |
}(resolver); | |
} | |
var getNamespace = function(nodeName) { | |
if (nodeName.indexOf(':') > -1) { | |
prefix = nodeName.substr(0, nodeName.indexOf(':')) || ''; | |
} else { | |
prefix = '#default'; | |
} | |
return lookupNamespaceURI(prefix); | |
}; | |
var appendTo = function(target, value) { | |
var i; | |
if (value instanceof Node) { | |
node.appendChild(value.cloneNode(true)); | |
} else if (value instanceof Array) { | |
for (i = 0; i < value.length; i++) { | |
appendTo(target, value[i]); | |
} | |
node.appendChild(dom.createTextNode(value)); | |
} else if (value instanceof Object){ | |
for (i in value) { | |
if (!value.hasOwnProperty(i)) { continue; } | |
node.setAttributeNS(getNamespace(i), i, value[i]); | |
} | |
} else if (typeof value == 'string') { | |
node.appendChild(dom.createTextNode(value.toString())); | |
} | |
}; | |
var XMLCreator = function(name) { | |
node = dom.createElementNS(getNamespace(name), name); | |
for (var i = 1; i < arguments.length; i++) { | |
appendTo(node, arguments[i]); | |
} | |
return node; | |
}; | |
XMLCreator.cdata = function(content) { | |
return dom.createCDATASection(content); | |
}; | |
XMLCreator.comment = function(content) { | |
return dom.createComment(content); | |
}; | |
XMLCreator.pi = function(content) { | |
return dom.createProcessingInstruction(content); | |
}; | |
return XMLCreator; | |
}; | |
var $_; | |
$_ = XMLCreatorFactory(); | |
console.log( | |
$_( | |
'ul', | |
$_('li', 'bar', {class : 'foo'}) | |
) | |
); | |
$_ = XMLCreatorFactory(true, {atom : 'urn:atom'}); | |
console.log( | |
$_( | |
'atom:feed', | |
$_('atom:title', 'bar'), | |
$_.cdata('test') | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment