How can I load a XML file to class using Javascript?
I'm not aware of a built-in XML serializer/deserializer in JavaScript. Is you considered something native to JavaScript, like JSON?
Here is an XML to JSON Javascript converter that might steer you in the right direction.
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
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.