// Created by Brian LePore (brian.lepore@gmail.com)
// Copyright 2005.
// Version 1.1.1 (updated on 7/5/06).
// Code is free to use, as long as you give me credit and alert me to any bugs.

function toDOM(XML, parent) {
   if (!XML || (typeof parent != 'object') || !document.createElement || (XML.indexOf('<') == -1)) return;
   var Types = [];
   var nodes = XML.split('<');
   // first take care of base node
   var txt = document.createTextNode(nodes[0]); parent.appendChild(txt);
   var i = 1, j, k;
   while (i < nodes.length) {
      var node = nodes[i];
      var end = node.indexOf('>');
      var txt = document.createTextNode(node.substring(end+1));
      var name = node.replace(/^\/?(\w+).*/, "$1|");
      name = name.substring(0, name.indexOf('|'));
      if (!Types[name]) Types[name] = document.createElement(name);
      var element = Types[name].cloneNode(false);
      var attributes = node.substring(name.length, end).split('=');
      for (j = 0; j < attributes.length-1; j++) {
         attName  = attributes[j].replace(/^(\s*('|").*?\2)?\s+(\w+)\s*$/, "$3");
         attValue = attributes[j+1].replace(/^\s*('|")(.*?)\1\s*.*$/, "$2");
         element.setAttribute(attName, attValue);
      }
      
      /*check if self closes */
      if (node.charAt(end-1) == '/') {
         parent.appendChild(element);
         parent.appendChild(txt);
      /* otherwise, find where it closes */
      } else {
         for (j = i+1; j < nodes.length; j++) {
            if (nodes[j].substring(0, name.length+1) == ("/" + name)) {
               element.appendChild(txt);
               var string = '';
               for (k = i+1; k < j; k++) string += '<' + nodes[k];
               if (string.length) element = toDOM(string, element);
               parent.appendChild(element);
               var after = nodes[j].substring(nodes[j].indexOf('>')+1);
               after = document.createTextNode(after);
               parent.appendChild(after);
               i = j;
               break;
            }
         }
      }
      
      i++;
   }
   return parent;
}