tags:

views:

299

answers:

4

How can I load a XML file to class using Javascript?

A: 

I'm not aware of a built-in XML serializer/deserializer in JavaScript. Is you considered something native to JavaScript, like JSON?

Jason
And JSON can be dynamically loaded?
Yes, JSON can be loaded dynamically. See jQuery's getJSON method at http://docs.jquery.com/Ajax/jQuery.getJSON
Jason
A: 

Here is an XML to JSON Javascript converter that might steer you in the right direction.

cletus
Thanks for the link. How can I load JSON in a class?
+6  A: 

Unfortunately, each browser presents its own way of parsing a string containing XML. Here are the ways that I know of for each of the big 3 browsers. Please note, I haven't had a chance to try each of these as they're cobbled together from various blogs and my own memory.

Firefox has an object called DOMParser that can be used to parse XML in a string. The API is pretty simple -- instantiate the DOMParser and call its parseFromString method. Here is an example:

var xmlString = '<?xml version="1.0"?>...';
var parser = new DOMParser();
var dom = parser.parseFromString(theString, "text/xml");
// use dom

IE uses the Microsoft ActiveX XMLDOM control, therefore you must instantiate the DOM control and use its methods, again here's an example:

var xmlString = '<?xml version="1.0"?>...';
dom=new ActiveXObject("Microsoft.XMLDOM");
dom.async="false";
dom.loadXML(xmlString);
// use dom

And lastly, the weirdo Safari version. Safari doesn't have a parser built in, and being that it doesn't run on Windows it doesn't support ActiveX controls. However, Safari does support data: urls. In Safari a URL with the document is created and called through an XMLHTTPRequest. Like all XMLHttpRequests, you use the standard responseXml property of the XMLHttpRequest to access the DOM.

var xmlString = '<?xml version="1.0"?>...';
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(xmlString);

var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);

var dom = xhr.responseXML;
// Use dom here
Bryan Kyle
Actually Safari runs on Windows, but that of course doesn't change the fact that it's unable to use ActiveX. +1.
Luca Matteis
A: 

This code will work for all kind of browsers

var url="file.xml"
var xmlDoc="";
if(window.XMLHttpRequest&&!window.ActiveXObject)
{
    var Gz=new XMLHttpRequest();Gz.open('GET',url,false);Gz.send(null);xmlDoc=Gz.responseXML;
}
else
{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.load(url);
}

After using this, you can parse the tag and retrieve the data.

praveenjayapal