程序员

不同浏览器对XML的解析是不同的

作者:admin 2021-04-06 我要评论

下面这段代码在火狐能够解析,在谷歌和IE就不行了,应该如何来修改代码?如何解析XML呢? JScript code: 复制代码 代码如下: $("#result").append(xmlDoc.first...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
下面这段代码在火狐能够解析,在谷歌和IE就不行了,应该如何来修改代码?如何解析XML呢?
JScript code:
复制代码 代码如下:

$("#result").append(xmlDoc.firstChild.localName + "<br/><hr>");
for ( var i = 0; i < xmlDoc.documentElement.childElementCount; i++) {
$("#result").append(
xmlDoc.documentElement.children[i].localName + "<br/>");
}

兼容 IE、Firefox、Chrome、Safari、Opera 等浏览器的XML文件加载方式的代码如下,xml文件名为 1.xml。
XML代码
XML code:
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<note>
<t1>
<title>孟子E章的网站</title>
<url>http://dotnet.aspx.cc/</url>
</t1>
<t1>
<title>孟宪会的博客</title>
<url>http://blog.csdn.net/net_lover/</url>
</t1>
</note>

HTML 代码
HTML code:
复制代码 代码如下:

<script type="text/javascript">
var xmlDoc = null, xmlhttp = null;
function loadXML() {
xmlhttp = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
if (xmlhttp == null) {
alert("你的浏览器不支持 XMLHttpRequest");
return;
}
xmlhttp.open("GET", "1.xml?" + Date.parse(new Date()), true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.onreadystatechange = getmessage;
xmlhttp.send(null);
}
function getmessage() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML.documentElement;
if (xmlDoc == null) {
alert("返回的数据不正确。");
return;
}
var nodes = xmlDoc.getElementsByTagName("t1")
tb = document.getElementById("table_note");
tbody = document.createElement("tbody")
for (i = 0; i < nodes.length; i++) {
tr = document.createElement("tr")
td = document.createElement("td")
td.innerHTML = nodes[i].getElementsByTagName("title")[0].childNodes[0].nodeValue
tr.appendChild(td)
td = document.createElement("td")
url = nodes[i].getElementsByTagName("url")[0].childNodes[0].nodeValue;
td.innerHTML = "<a href='" + url + "'>" + url + "</a>"
tr.appendChild(td)
tbody.appendChild(tr)
}
tb.appendChild(tbody)
}
}
</script>
</head>
<body onload="loadXML()">
<table id="table_note" border="1">
<tr>
<td>姓名</td>
<td>网址</td>
</tr>
</table>
</body>
</html>

本文转载自网络,原文链接:https://m.jb51.net/article/32531.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • Vue SPA 首屏优化方案

    Vue SPA 首屏优化方案

  • vue 动态添加的路由页面刷新时失效的原

    vue 动态添加的路由页面刷新时失效的原

  • vue项目配置 webpack-obfuscator 进行

    vue项目配置 webpack-obfuscator 进行

  • JavaScript 中的执行上下文和执行栈实

    JavaScript 中的执行上下文和执行栈实

腾讯云代理商
精彩导读
海外云服务器
热门资讯
腾讯云代理商