Javascript – DOM – Convert XML DOM object to friendly array.

Use this simple javascript function to convert any loaded xml string to a hash/array format variable.

var toDOM = function(node, obj) {
node = !node.nodeName ? (new DOMParser()).parseFromString(node, “text/xml”).firstChild : node;
obj = obj && obj != ‘undefined’ ? obj : {};
if (!node.nodeName || node.nodeName == ‘undefined’) return(obj);
if (node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attr = node.attributes[i];
obj[attr.name.toLowerCase()] = attr.value;
}
}
if (node.childNodes.length) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
var objchild = {};
if (node.getElementsByTagName(child.tagName).length > 1) {
if (!obj[child.nodeName.toLowerCase()]) obj[child.nodeName.toLowerCase()] = [];
obj[child.nodeName.toLowerCase()][obj[child.nodeName.toLowerCase()].length] = toDOM(child, {});
} else if (child.nodeName && child.nodeName != ‘#cdata-section’) {
obj[child.nodeName.toLowerCase()] =  child.nodeName != ‘#text’ ? toDOM(child, {}) : child.value;
} else obj['value'] = obj['value'] ? obj['value'] + child.nodeValue : child.nodeValue;
}
}
return(obj);
}

Note that all elements / attributes are transformed to lowercase. – and sorry there are not much of documentation in code

  1. Next post: How to embed images in email using cakePHP (not just attach it to the message)
  2. Previous post: CakePHP Helper – the fetcher, what we all need, as simple as it is
  • hazel Blossom


    Thanks for sharing
    your great ideas with us through this site.definition essay writing

  • Parajumpers Jackets Canada

    It has every
    single on
    the essence news so when I take
    to imply
    this web
    page that I've
    been exceptionally
    constructive and I presume
    it pretty
    obligatory all group of
    individuals. 

  • 19891001jing
  • Hi, I appreciate the information that you have provided in the post. It is worth noting and I really liked the presentation as well. I will surely come back for more of interesting posts.

  • Nce to be visiting your blog again, it has been months for me.Well this article that i've been waited for so long.I need this article to complete my assignment in the college, and it has same topic with your article.Thanks, great share.

blog comments powered by Disqus