简体   繁体   English

如何通过 javascript 向 IE 中的 XML 添加额外的 xmlns 命名空间属性

[英]How to add additional xmlns namespace attributes to XML in IE via javascript

I'm a little bit stuck trying to attach multiple namespaces to an XML element via javascript across browsers;我在尝试通过跨浏览器的 javascript 将多个命名空间附加到 XML 元素时有点卡住了; I've tried about a dozen different ways to no avail.我尝试了十几种不同的方法都无济于事。

I usually use plain old javascript but for the sake of keeping this example short, this is how what I'm doing would be done via jQuery:我通常使用普通的旧 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");

In both Chrome and FF, this works as expected giving a result like this:在 Chrome 和 FF 中,这都按预期工作,结果如下:

<soapenv:Envelope 
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

But in IE9, I get a result like this:但是在 IE9 中,我得到这样的结果:

<soapenv:Envelope 
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:NS1="" NS1:xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

And I cannot find a way to add this namespace attribute without IE9 adding this NS1 prefix to my namespaces.如果没有 IE9 将此 NS1 前缀添加到我的命名空间,我无法找到添加此命名空间属性的方法。 Also if I try passing this result back into $.parseXML(result) I get a malformed XML exception.此外,如果我尝试将此结果传递回 $.parseXML(result) ,则会出现格式错误的 XML 异常。

Am I misunderstanding something to do with the way namespaces are declared in IE or can anyone suggest a way I can get a consistent result across browsers?我是否误解了与在 IE 中声明命名空间的方式有关,或者有人可以建议我可以在浏览器中获得一致结果的方法吗?

Thanks in advance提前致谢

In case anyone else runs into a similar problem to this, I ended up finding out that it can be fixed by initialising the IE XML DOM object differently to the way jQuery does it.如果其他人遇到与此类似的问题,我最终发现可以通过以与 jQuery 不同的方式初始化 IE XML DOM 对象来修复它。 I used something similar to the following and now the xml namespaces seem to be working fine across all major browsers and the jQuery attr method will now work again also.我使用了类似于以下内容的内容,现在 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM