Page 1
Index
See this article in english  Ver este artículo en español 
Page 2
Browser independant XPath evaluation

Getting an XML representation of the current HTML document

Alexander Hristov

This small function creates an XML representation (DOM compliant) of the current HTML document. It is only necessary for Internet Explorer, as on Mozilla and other browsers the HTML nodes are already XML nodes.

doc2dom.js
 
function document2DOM() {
  var root = new ActiveXObject("MSXML.DOMDocument");
  root.async = false;
  root.resolveExternals = false;
  loadNode(root,root,document);
  return root;
}

function loadNode(root,parentNode,htmlNode) {
  switch (htmlNode.nodeType) {
    // Comment node
    case 8 : 
      parentNode.appendChild( root.createComment( htmlNode.nodeValue ) );
      return;
      
    // CDATA section
    case 4:
      parentNode.appendChild( root.createCDATASection( htmlNode.nodeValue ) );
      return;
      
    // Text node  
    case 3 :
      parentNode.appendChild( root.createTextNode( htmlNode.nodeValue) );
      return;
      
    // Document Node
    case 9 :
      var children = htmlNode.childNodes;
      for (var i = 0; i < children.length; i++) {
        loadNode(root,root,children[i]);
      }
      return;
      
    // Element node  
    case 1 :
      var element = root.createElement( htmlNode.nodeName ) 
      parentNode.appendChild(element);
      
      // Set all attributes
      for (var i = 0; i < htmlNode.attributes.length; i++) {
        var attr = htmlNode.attributes[i];
        if (attr.nodeValue && attr.specified) {
          var attrNode = root.createAttribute(attr.nodeName);
          attrNode.value = attr.nodeValue;
          element.setAttributeNode(attrNode);
        }
      }
      
      // Now process the children
      var children = htmlNode.childNodes;
      for (var i = 0; i < children.length; i++) {
        loadNode(root,element,children[i]);
      }
      return;
  }
}

function test() {
  var result = document2DOM();
  alert(result.xml)
}

 

Press   to test this function. (Internet Explorer only)



Source code



 

Comments

Feb 24, 2008 at 03:45 Sent by Romita
Very good tutorial, would u help me with some doubts?

 

Add a Comment

Name (optional)
EMail (optional, will not be displayed)

Text