10.為XML文件提供Html格式
XML的一個優點是把HTML文檔和它的數據分離開。通過使用浏覽器中的XML parser,Html頁面可以被構造成靜態文檔,
通過JavaScript提供動態數據。下面的例子使用Javascript讀取XML文檔,寫XML數據成Html元素:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.load("note.XML")
nodes = XMLDoc.documentElement.childNodes
to.innerText = nodes.item(0).text
from .innerText = nodes.item(1).text
header.innerText = nodes.item(2).text
body.innerText = nodes.item(3).text
11.通過名稱訪問XML元素
下面的例子使用JavaScript讀取XML文檔,寫XML數據成Html元素:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.load("note.XML")
document.write(XMLDoc.getElementsByTagName("from").item(0).text)
12.裝載純XML文本進入parser
下面的代碼裝載文本字符串進入XML parser :
<script language="JavaScript">
var text="<note>"
text=text+"<to>Tove</to><from>Jani</from>"
text=text+"<heading>Reminder</heading>"
text=text+"<body>Don't forget me this weekend!</body>"
text=text+"</note>"
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.loadXML(text)
// ....... PRocessing the document goes here
</script>
13.裝載XML進入Parser
<Html>
<body>
<script language="Javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.load("note.XML")
document.write("The first XML element in the file contains: ")
document.write(XMLDoc.documentElement.childNodes.item(0).text)
</script>
</body>
</Html>
遍歷XML節點樹:
<Html>
<body>
<script language="VBScript">
txt="<h1>Traversing the node tree</h1>"
document.write(txt)
set xmlDoc=CreateObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.load("note.XML")
for each x in XMLDoc.documentElement.childNodes
document.write("<b>" & x.nodename & "</b>")
document.write(": ")
document.write(x.text)
document.write("<br>")
next
</script>
</body>
</Html>
裝載XML 進入 Html
<Html>
<head>
<script language="JavaScript"
for="window" event="onload">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
XMLDoc.async="false"
xmlDoc.load("note.XML")
nodes = XMLDoc.documentElement.childNodes
to.innerText = nodes.item(0).text
from.innerText = nodes.item(1).text
header.innerText = nodes.item(2).text
body.innerText = nodes.item(3).text
</script>
<title>Html using XML data</title>
</head>
<body bgcolor="yellow">
<h1>Refsnes Data Internal Note</h1>
<b>To: </b><span id="to"></span>
<br>
<b>From: </b><span id="from"></span>
<hr>
<b><span id="header"></span></b>
<hr>
<span id="body"></span>
</body>
</Html>