JavaScript - Import XML Document

 

function importXML()
{
    
if (document.implementation && document.implementation.createDocument)
    
{
        xmlDoc 
= document.implementation.createDocument(""""null);
        xmlDoc.onload 
= createTable;
    }

    
else if (window.ActiveXObject)
    
{
        xmlDoc 
= new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.onreadystatechange 
= function () {
            
if (xmlDoc.readyState == 4) createTable()
        }
;
     }

    
else
    
{
        alert(
'Your browser can\'t handle this script');
        return;
    }
    xmlDoc.load("emperors.xml");
}

function createTable()
{
    var x = xmlDoc.getElementsByTagName(
'emperor');
    var newEl = document.createElement(
'TABLE');
    newEl.setAttribute(
'cellPadding',5);
    var tmp = document.createElement(
'TBODY');
    newEl.appendChild(tmp);
    var row = document.createElement(
'TR');
    for (j=0;j<x[0].childNodes.length;j++)
    {
        if (x[0].childNodes[j].nodeType != 1) continue;
        var container = document.createElement(
'TH');
        var theData = document.createTextNode(x[0].childNodes[j].nodeName);
        container.appendChild(theData);
        row.appendChild(container);
    }
    tmp.appendChild(row);
    for (i=0;i<x.length;i++)
    {
        var row = document.createElement(
'TR');
        for (j=0;j<x[i].childNodes.length;j++)
        {
            if (x[i].childNodes[j].nodeType != 1) continue;
            var container = document.createElement(
'TD');
            var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
            container.appendChild(theData);
            row.appendChild(container);
        }
        tmp.appendChild(row);
    }
    document.getElementById(
'writeroot').appendChild(newEl);
}

Importing the XML
First of all I import the XML document and make it accessible through the object xmlDoc. When the document has finished loading, I want the script createTable() that construes the table to be executed immediately. Of course, the coding for all this is browser specific.

Clicking the link activates the function importXML.

function importXML()
{

Mozilla
Netscape imports an XML document through the method document.implementation.createDocument(). First check if document.implementation is supported, then check if document.implementation.createDocument() is supported. Explorer 5 on Mac also supports document.implementation, but not the createDocument method, so it shouldn
't execute this script.

    
if (document.implementation && document.implementation.createDocument)
    
{

Then create the document and give it an onLoad event handler: as soon as the document has been loaded the script createTable() is executed, creating the table:

        xmlDoc 
= document.implementation.createDocument(""""null);
        xmlDoc.onload 
= init;
    }


Explorer
Explorer on Windows doesn
't support document.implementation . Instead, you must create an Active X Object that will contain the XML document. So we see if the browser can create ActiveXObjects:

    else if (window.ActiveXObject)
    {

If it does, we can proceed by creating the object

        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

Unfortunately there
's no onLoad event for this object. To see if it's ready we should use the MS proprietary ReadyStateChange event. I don't quite understand all this myself, but it works. When the onReadyStateChange event handler fires, the readyState has a value between 1 and 44 means that all data has been received (= onLoad). So if it's 4, start creating the table.

        xmlDoc.onreadystatechange = function () {
            if (xmlDoc.readyState == 4) createTable()
        };
    }

Other browsers
If the browser supports neither way, give an alert and end everything:

    else
    {
        alert(
'Your browser can\'t handle this script');
        
return;
    }


/**
 * Create a new Document object. If no arguments are specified,
 * the document will be empty. If a root tag is specified, the document
 * will contain that single root tag. If the root tag has a namespace
 * prefix, the second argument must specify the URL that identifies the
 * namespace.
 
*/

XML.newDocument 
= function(rootTagName, namespaceURL) {
  
if (!rootTagName) rootTagName = "";
  
if (!namespaceURL) namespaceURL = "";
  
if (document.implementation && document.implementation.createDocument) {
    
// This is the W3C standard way to do it
    return document.implementation.createDocument(namespaceURL, rootTagName, null);
  }

  
else // This is the IE way to do it
    // Create an empty document as an ActiveX object
    // If there is no root element, this is all we have to do
    var doc = new ActiveXObject("MSXML2.DOMDocument");
    
// If there is a root tag, initialize the document
    if (rootTagName) {
      
// Look for a namespace prefix
      var prefix = "";
      
var tagname = rootTagName;
      
var p = rootTagName.indexOf(':');
      
if (p != -1{
        prefix 
= rootTagName.substring(0, p);
        tagname 
= rootTagName.substring(p+1);
      }

      
// If we have a namespace, we must have a namespace prefix
      // If we don't have a namespace, we discard any prefix
      if (namespaceURL) {
        
if (!prefix) prefix = "a0"// What Firefox uses
      }

      
else prefix = "";
      
// Create the root element (with optional namespace) as a
      // string of text
      var text = "<" + (prefix?(prefix+":"):""+  tagname +
          (namespaceURL
           
?(" xmlns:" + prefix + '="' + namespaceURL +'"')
           :
""+
          
"/>";
      
// And parse that text into the empty document
      doc.loadXML(text);
    }

    
return doc;
  }

}
;

posted @   龍的傳人  阅读(815)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示