fwoncn
fwoncn

Reputation: 189

How to create and use a XML document object properly considering browser compatibility?

Now I'm working on a web project. I need to create a XML document object using a given string buffer in JavaScript. I've successfully made it run smoothly on IE, but apparently I need to do some more work to improve its compatibility.

Here is a tiny example describing what I want to express (Note, all in JavaScript) first of all, we have a string variable, say, "buffer", which has been obtained from the server and, in fact, it is formed like a XML:

"<Messages><Item>aaa</Item><Item>bbb</Item></Messages>"

Then, I can use the following code segment to create a IE-recognizable XML doc object:

var xmlDoc = new ActiveXObject("Microsoft.xmlDOM");
xmlDoc.async = false;
xmlDoc.loadXML(buffer);

And we've got it.

So, what I want to know is how to create an object considering browser compatibility (firefox, opera, etc) and whether the usages of it are same.

Upvotes: 2

Views: 4056

Answers (1)

Brian Campbell
Brian Campbell

Reputation: 333026

DOMParser should work. It is not a standard, but it is supported at least on WebKit (Safari, Chrome, etc), and Gecko (Firefox); I don't know about Opera:

var buffer = "<Messages><Item>aaa</Item><Item>bbb</Item></Messages>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(buffer, "text/xml");

Upvotes: 5

Related Questions