JavaScript - Import XML Document

本文介绍了一种使用JavaScript从不同浏览器环境中加载并解析XML文件的方法。通过创建HTML表格展示XML数据,实现了跨浏览器兼容性。文章详细说明了针对Mozilla、Netscape及Internet Explorer等浏览器的不同实现方式。

 

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;
  }

}
;

转载于:https://www.cnblogs.com/jacklong/archive/2008/01/10/1033980.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值