如何在javascript中向XML添加其他xmlns命名空间属性

2po*_*kes 6 javascript xml jquery

我试图通过浏览器中的javascript将多个命名空间附加到XML元素上有点困难..我尝试了十几种不同的方法无济于事:(我通常使用普通的旧javascript但是为了这个缘故保持这个例子简短,这就是我正在做的事情将通过jQuery完成:

var soapEnvelope = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"></soapenv:Envelope>';
var jXML = jQuery.parseXML(soapEnvelope);
$(jXML.documentElement).attr("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
Run Code Online (Sandbox Code Playgroud)

在Chrome和FF中,这可以按预期工作,得到如下结果:

<soapenv:Envelope 
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
Run Code Online (Sandbox Code Playgroud)

但是在IE9中,我得到了这样的结果:

<soapenv:Envelope 
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:NS1="" NS1:xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
Run Code Online (Sandbox Code Playgroud)

如果没有IE9将这个NS1前缀添加到我的命名空间,我找不到添加此命名空间属性的方法.此外,如果我尝试将此结果传回$ .parseXML(结果),我会收到格式错误的XML异常.

我是否误解了与IE中声明命名空间的方式有关或者有人建议我可以在浏览器中获得一致的结果吗?

提前致谢

2po*_*kes 4

如果其他人遇到与此类似的问题,我最终发现可以通过与 jQuery 不同的方式初始化 IE XML DOM 对象来解决该问题。我使用了类似于下面的内容,现在 xml 命名空间似乎在所有主要浏览器上都能正常工作,并且 jQuery attr 方法现在也将再次工作。

var getIEXMLDOM = function() {
  var progIDs = [ 'Msxml2.DOMDocument.6.0', 'Msxml2.DOMDocument.3.0' ];
  for (var i = 0; i < progIDs.length; i++) {
    try {
        var xmlDOM = new ActiveXObject(progIDs[i]);
        return xmlDOM;
    } catch (ex) { }
  }
  return null;
}

var xmlDOM;
if ( $.browser.msie ) {
   xmlDOM = getIEXMLDOM();
   xmlDOM.loadXML(soapEnvelope);
} else {
   xmlDOM = jQuery.parseXML(soapEnvelope);
}

$(xmlDOM.documentElement).attr("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
Run Code Online (Sandbox Code Playgroud)