Synopsis
- Collect the xml through an ajax call.
- Xml response available as dom tree (parsed) or in lexical representation (text)
- Have the callback handler process your xml and interact with the dom
- options to process your xml:
- XPath
- Xslt
- DOM functions
- string manipulation
- string parsing ( probably pointless, unless you have special requirements on parsing )
Code
A pure Javscript solution using the XMLHttpRequest ( docs: eg. MDN reference, MDN usage hints; there also exists a tutorial on html5rocks ) might look similar to the following fragment:
var oReq = new XMLHttpRequest();
function eh_onload ( ) {
var xmlhttp = this;
if (xmlhttp.readyState === 4) {
console.log ( "xmlhttp.status = " + xmlhttp.status);
if (xmlhttp.status === 200) {
//
// process your xml here.
//
console.log ( "responseText = '" + xmlhttp.responseText + "'");
console.log ( "xml root element = '" + xmlhttp.responseXML.documentElement.nodeName + "'");
}
else {
console.log('error');
}
}
}
oReq.onload = eh_onload;
oReq.open("get", "http://wsearch.nlm.nih.gov/ws/query?db=digitalCollections&term=cholera", true);
oReq.send();
The code snippet performs an ajax request and registers a callback that will be executed upon completion of the request. As you can see, you may either access the lexical representation of the xml data received or a parsed DOM structure.
Alternative
In case using the jquery library is acceptable to you, you may proceed along the lines of the following code sample:
function eh_xml ( parsedxml, textStatus, jqXHR ) {
// process your xml here.
//
console.log ( "typeof(parsedxml) = '" + typeof(parsedxml)+ "'");
console.log ( "$('term', parsedxml).length = " + $("term", parsedxml).length);
}
$.ajax({
url: "http://wsearch.nlm.nih.gov/ws/query?db=digitalCollections&term=cholera"
, dataType: "xml"
, success: eh_xml
});
The code snippet performs an ajax request and provides a callback that receives the xml in parsed (DOM) representation.
Note & Caveat
The code sample uses a public web service provided by the US NIH returning xml data. This one has been selected randomly and is employed for the sole purpose to have a working PoC. No affiliations exist and the usual legal disclaimers apply.
The code can be tested from the console (eg. in Chrome) opened on the site http://wsearch.nlm.nih.gov/ using the following prelude which loads the jquery library in the context of the site hosting the web service:
var script = document.createElement("script");
script.src = "http://code.jquery.com/jquery-2.1.3.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);