获取 XML 文件,然后将与号“&”替换为“and”

由于“&”等符号,浏览器没有读取 xml 文件。我想获取 xml 文件并将所有“&”替换为“and”。是否可以?


我尝试使用替换功能,但它不起作用: 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;

这是我的odds3.xml,它有&.


<match id="32375537" he="Brighton & Hove Albion">

我希望输出显示我的odds3.xml 中的数据,&然后替换为and. 谢谢您的帮助!


控制台日志: 我添加了 console.log(xml) 但它返回了“null”值,因为 xml 文件上有“&”。

http://img3.mukewang.com/6183aa65000191ff07580441.jpg

预期输出:

MATCH: id: 32375537 he: Brighton and Hove Albion


潇湘沐
浏览 281回答 2
2回答

海绵宝宝撒

jsfiddle 链接中提到的解决方案。替换 responseText 上的字符而不是 responseXml。您可以在成功替换所需字符后将该 xmltext 转换为 xmldocument。http://jsfiddle.net/ogaq9ujw/2/&nbsp;var response=request.responseText; var xmlText=response.replace('GM',"and");

收到一只叮咚

1) 你的请求是同步的,因为你使用了 send(...,FALSE)。在您的情况下,异步不是问题。2) 使用console.log (xml) 签入控制台。不要在 html页面中显示它并注释替换行,因为此 var 的内容显示可以实时更改,随时可以更改。看看它是否真的是一个pur & in属性。var xml = request.responseXML;/* var xml = xml.replace (/&/g, "and"); */console.log (xml);3) 但是:& 在属性 xml 中无效,必须替换为 & 在 xml 的制作过程中。谁生成这个 xml 文件?您或第三方服务,或其他程序员?4) 替换 & 不是解决方案:想象一下,稍后在 xml 中,您找到了一个有效的字符串<text> here &amp; there </text>它会变成<text> here and;amp; there </text>5) 尝试使用 responseText 而不是 xmlResponse :这是浏览器尝试解析它之前的完整原始响应。var xhr = new XMLHttpRequest();xhr.open('GET', '/ODDS/odds3.xml');xhr.onload = function() {&nbsp; &nbsp; if (xhr.status === 200) {&nbsp; &nbsp; &nbsp; &nbsp; alert('response is' + xhr.responseText);&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; alert('Request failed.&nbsp; Returned status of ' + xhr.status);&nbsp; &nbsp; }};xhr.send();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript