2potatocakes
2potatocakes

Reputation: 2260

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

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:

<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:

<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. Also if I try passing this result back into $.parseXML(result) I get a malformed XML exception.

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?

Thanks in advance

Upvotes: 6

Views: 3525

Answers (1)

2potatocakes
2potatocakes

Reputation: 2260

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. 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.

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");

Upvotes: 4

Related Questions