花了一點時間把程式湊出來,
大部分的程式碼都是用網路上找到的,
主要的收穫就是要在IE中要讀取本地端的檔案,
需要透過一些技巧, (activex或java applet之類)
還得解決相對路徑的問題,
整個程式碼會變成這樣.
ps. 相關的參考資料在註解
function ShowFileInfo(filespec){
var fso, f, ForReading = 1, ForWriting = 2;
//reference: http://msdn.microsoft.com/en-us/library/t58aa4dd%28v=VS.85%29.aspx
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filespec, ForReading);
// Read from the file.
if (f.AtEndOfStream)
text="";
else
text=f.ReadAll();
//reference: http://www.w3schools.com/xml/xml_parser.asp
var xmlDoc;
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
var x=xmlDoc.getElementsByTagName("book");
document.write("Read XML file->"+filespec+"
The title of Book in XML:
");
for (i=0;i {
document.write("
");
}
document.write("
<table>
<tbody>
<tr>
<td>");
document.write(i+': '+x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("</td>
</tr>
</tbody>
</table>
");
}
//reference: http://wd.iworld.com/forum/showthread.php?t=86528
String.prototype.toLocalPath=function(){
return unescape(this.slice(this.search(/[A-Z]:\/[^\/]/i)).replace(/\//g,'\\'))
};
String.prototype.folderOf=function(no_slash){
return this.slice(0,this.lastIndexOf('\\',this.length-(/\\$/.test(this)?2:0))+(no_slash?0:1))
};
var app_path=location.href.toLocalPath().folderOf();
alert('Reading: '+app_path+'books.xml')
ShowFileInfo(app_path +"books.xml");
沒有留言:
張貼留言