如何通过javascript向IE中的XML添加额外的xmlns命名空间属性
我在尝试通过跨浏览器的javascript将多个名称空间附加到XML元素时遇到了一些困难;我试过十几种不同的方法,但都没有用 我通常使用普通的老javascript,但为了保持这个示例的简短性,我将通过jQuery执行以下操作:如何通过javascript向IE中的XML添加额外的xmlns命名空间属性,javascript,jquery,xml,internet-explorer,Javascript,Jquery,Xml,Internet Explorer,我在尝试通过跨浏览器的javascript将多个名称空间附加到XML元素时遇到了一些困难;我试过十几种不同的方法,但都没有用 我通常使用普通的老javascript,但为了保持这个示例的简短性,我将通过jQuery执行以下操作: var soapEnvelope = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"></soapenv:Envelope>'; var j
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");
var-soapEnvelope='';
var jXML=jQuery.parseXML(soapEnvelope);
$(jXML.documentElement).attr(“xmlns:xsd,”http://www.w3.org/2001/XMLSchema");
在Chrome和FF中,这都能正常工作,产生如下结果:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:NS1="" NS1:xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
但在IE9中,我得到如下结果:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:NS1="" NS1:xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
如果IE9不将NS1前缀添加到我的命名空间中,我就无法找到添加此命名空间属性的方法。此外,如果我尝试将此结果传递回$.parseXML(result),则会得到一个格式错误的XML异常
我是否误解了IE中名称空间的声明方式,或者有人能提出一种方法让我在浏览器中获得一致的结果
提前感谢如果其他人遇到类似的问题,我最终发现可以通过与jQuery不同的方式初始化IE XML DOM对象来解决这个问题。我使用了与下面类似的东西,现在xml名称空间似乎在所有主要浏览器中都可以正常工作,jQueryAttr方法现在也可以工作了
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");
var getIEXMLDOM=function(){
var progIDs=['Msxml2.DOMDocument.6.0','Msxml2.DOMDocument.3.0'];
对于(变量i=0;i
+1。无论如何,您应该修改浏览器测试。目前您更喜欢专有方法,但IE 9+支持jQuery内部默认的window.DOMParser
。如果($.browser.msie),不要执行,如果(!window.DOMParser)
,请执行。另外,下面是关于在MSXML中创建名称空间声明的一个很好的总结:没有jQuery:var objXmlDomParser=new DOMParser();xmlDOM=objXmlDomParser.parseFromString(soapEnvelope,“text/xml”);xmlDOM.documentElement.setAttribute(“xmlns:xsd”)和旧IE:xmlDOM.setProperty(“SelectionNamespaces”,“xmlns:xsd=”)@Tomalak即使使用IE11,使用jQuery默认解析器也会产生2potatocakes提到的问题。我发现,在不使用自定义浏览器代码的情况下,最好的方法是在调用parseXML之前设置所有名称空间。