Reputation: 81
The browser is not reading the xml file because of ampersands like "&". I'd like to get the xml file and replace all "&" to "and". Is it possible?
I tried using replace function but it's not working:
var xml = xml.replace(/&/g, "and");
var request = new XMLHttpRequest();
request.open("GET", "/ODDS/odds3.xml", false);
request.send();
var xml = request.responseXML;
var xml = xml.replace(/&/g, "and");
var txt = "";
var txt2 = "";
var txt3 = "";
var users = xml.getElementsByTagName("match");
for (var i = 0; i < users.length; i++) {
var names = users[i];
for (j = 0; j < names.length; j++) {
txt += "MATCH: " + " id: " + names[j].getAttribute('id') + " he: " + names[j].getAttribute('he') + " < br > ";
}
}
document.getElementById("demo").innerHTML = txt;
This is my odds3.xml that has &
.
<match id="32375537" he="Brighton & Hove Albion">
I expected the output to display my datas from odds3.xml, from &
then replaced to and
. Thanks for the help!
CONSOLE LOG:
I added console.log(xml) but it returned "null" value, because the xml file have "&" on it.
Expected output:
MATCH: id: 32375537 he: Brighton and Hove Albion
Upvotes: 0
Views: 632
Reputation: 299
Solution mentioned in the jsfiddle link. Replace character on responseText not responseXml. you can convert that xmltext to xmldocument after successful replacement of required characters.
http://jsfiddle.net/ogaq9ujw/2/ var response=request.responseText;
var xmlText=response.replace('GM',"and");
Upvotes: 1
Reputation: 608
1) yout request is synchrone, because you use send(...,FALSE). Asynchronous thing is not a issue in your case.
2) Check in the console with a console.log (xml). Do not display it in an html page and comment the replace line because the display of the content of this var can be changed in real time, at any time. And see if it is really a pur & in attribute.
var xml = request.responseXML;
/* var xml = xml.replace (/&/g, "and"); */
console.log (xml);
3) however: & is not valid in attribute xml, it must be replaced by & during the production of the xml. Who produces this xml file? you or third party service, or another programmer?
4) replace the & is not a solution: imagine that later in the xml, you find a valid string
<text> here & there </text>
it would become
<text> here and;amp; there </text>
5) try to work with responseText, not xmlResponse : this is the full raw response before browser tries to parse it.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/ODDS/odds3.xml');
xhr.onload = function() {
if (xhr.status === 200) {
alert('response is' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Upvotes: 1