XML DOM介绍和例子(三)
发布时间:2006-10-14 2:39:05   收集提供:gaoqian
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>

 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50