0

由于“&”之类的与号,浏览器没有读取 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 文件上有“&”。 在此处输入图像描述

预期输出:

MATCH: id: 32375537 he: Brighton and Hove Albion
4

2 回答 2

1

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() {
    if (xhr.status === 200) {
        alert('response is' + xhr.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();
于 2019-10-01T08:26:52.483 回答
1

jsfiddle链接中提到的解决方案。替换 responseText 上的字符而不是 responseXml。成功替换所需字符后,您可以将该 xmltext 转换为 xmldocument。

http://jsfiddle.net/ogaq9ujw/2/ var response=request.responseText; var xmlText=response.replace('GM',"and");

于 2019-10-01T09:52:59.687 回答