关于在html中通过js解析xml相关问题:
假如你打算在自己的网页上使用上面的例子,则必须把 XML 文件放到自己的服务器上。否则,xmlDoc.load() 将产生错误 "Access is denied"。(当然一般不放在服务器上 Firefox和IE7+也可以运行,不过最好放在服务器上。)
方法一:通过把一个 XML 文档载入解析器中:
代码:text.html
<html>
<head>
<script type="text/javascript">
function parseXML(){
try{ // code for IE6, IE5
xmlDoc=new ctiveXObject("Microsoft.XMLDOM");
}catch(e){
try{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlDoc=ocument.implementation.createDocument("","",null);
}catch(e){
alert(e.message);
return;
}
}
xmlDoc.async = false;
xmlDoc.load("note.xml"); document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue; document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body οnlοad="parseXML()">
<h1>W3School.com.cn Internal Note</h1>
<p><b>To:</b><span id="to"></span><br/>
<b>From:</b><span id="from"></span><br/>
<b>Message:</b><span id="message"></span>
<p>
</body>
</html>
对应的note.xml:
<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<lastname>Simth</lastname>
</note>
注意:(a) 360浏览器无效;(b)不能将js代码放在body中,否则无效。
方法二:把 XML 文档解析到 XMLDOM 对象中:
(XMLHttpRequest对象只能访问http协议的地址。要把网页放到iia等服务器上才行。还有不能跨域。)代码:text1.html
<html>
<head>
</head>
<body >
<h1>W3School.com.cn Internal Note</h1>
<p><b>To:</b><span id="to"></span><br/>
<b>From:</b><span id="from"></span><br/>
<b>Message:</b><span id="message"></span>
<p>
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
alert(xmlhttp);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","1/note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
对应的note.xml:
<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<lastname>Simth</lastname>
</note>
注意:如果你是本机进行测试的话,除了火狐浏览器可以,其他浏览器都不行,执行到xmlhttp.open("GET","1/note.xml",false);会报错。