JS載入xml文檔執行個體
books.xml
複製代碼 代碼如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="children">
<title lang="en">www.jb51.net</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
loadxml.htm
複製代碼 代碼如下:
<html>
<head>
<script>
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load("books.xml");
document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue); }
catch(e){alert(e.message);}
</script>
</head>
<body>
</body>
</html>
下面的是載入與解析xml檔案的例子,但xml是自訂的字串,一般在後台語言中用的到。
<html> <head> <script type="text/javascript"> function parseXML() { text="<note>"; text=text+"<to>George</to>"; text=text+"<from>John</from>"; text=text+"<heading>Reminder</heading>"; text=text+"<body>Don't forget the meeting!</body>"; text=text+"</note>"; try //Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(text); } catch(e) { try //Firefox, Mozilla, Opera, etc. { parser=new DOMParser(); xmlDoc=parser.parseFromString(text,"text/xml"); } catch(e) { alert(e.message); return; } } 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 onload="parseXML()"> <h1>W3Schools Internal Note</h1> <p><b>To:</b> <span id="to"></span> <b>From:</b> <span id="from"></span> <b>Message:</b> <span id="message"></span> </p> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
如果看完了上面的執行個體可以看下下面的文章。
http://www.jb51.net/article/14604.htm