将 XML 加载到 DOM 中并替换 Microsoft.XMLDOM 的使用

Loading XML into the DOM and replacing usage of Microsoft.XMLDOM

本文关键字:XMLDOM Microsoft 替换 加载 XML DOM      更新时间:2023-09-26

我正在使用一些遗留代码,在许多地方都有代码可以从某个 url 获取 XML 数据。 这很简单。

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";           
xmlDoc.load(url);

在某些地方

var httpRequest= new ActiveXObject("Msxml2.XMLHTTP.6.0");
httpRequest.open('GET', url, false);
httpRequest.send(null);

在大多数情况下,我们从响应 XML 中选取结果。我在许多地方看到"Microsoft.XMLDOM"的使用已经过时,取而代之的是ActiveXObject("Msxml2.XMLHTTP.6.0")。对于其他浏览器,我应该使用标准的W3C XMLHttpRequest。这似乎没有任何问题。

问题在于加载结果 xml 字符串。我看到 loadXML 是在使用 "Microsoft.XMLDOM" 时定义的,而不是使用 ActiveXObject("Microsoft.XMLHTTP");

对于其他浏览器,建议使用DOMParser以及IE-11。

这就是我当时从 url 中检索信息所做的分析该信息,然后最终尝试将 XML 字符串加载到 DOM。我的主要问题是,在与Internet Explorer相关的操作XML时,我越来越困惑哪种解决方案是合适的,或者可能为时已晚。我想删除"Microsoft.XMLDOM"的使用,但要执行loadXML,我必须回到它。 有没有更好的方法来解决这个问题?

 // Get the information use either the XMLHttpRequest or ActiveXObject
 if (window.ActiveXObject || 'ActiveXObject' in window) {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        else if (window.XMLHttpRequest) {
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
    }
}
httpRequest.open('GET', url, false);
httpRequest.send();
var xmlDoc = httpRequest.responseXML;
// Retrieve the XML into the DOM
var xml = xmlDoc.getElementsByTagName("XML_STRING_SETTINGS")

// Load the XML string into the DOM
if (window.DOMParser) {
    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(xml, "text/xml");
}
else // code for IE
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    // is there another way to do this load? 
    xmlDoc.loadXML(xml);
}

您可以采取以下步骤:

  1. 转到互联网选项。
  2. 选择"安全"选项卡。
  3. 在自定义级别下。
  4. 确保"初始化和编写活动 x 控件的脚本"未标记为"可安全编写脚本",选择启用的单选按钮,然后立即尝试运行代码。

我相信你的问题会得到解决。

我认为IE5和6的代码是

new ActiveXObject("Microsoft.XMLHTTP")

对于IE7+(和其他浏览器)

new XMLHttpRequest();