王新阳

wangxinyang

ASP遍历xml树

<%@ Language="VBScript" CODEPAGE="65001"%>
<%
Option Explicit
Session.CodePage=65001
Response.Charset="UTF-8"

Dim xmlStr, xml
xmlStr="<?xml version=""1.0"" encoding=""UTF-8""?>"&_
"<books>"&_
"	<book>"&_
"		<name>三国演义</name>"&_
"		<price>99</price>"&_
"	</book>"&_
"	<book>"&_
"		<name>水浒传</name>"&_
"		<price><![CDATA[22]]></price>"&_
"	</book>"&_
"</books>"

Set xml = Server.CreateObject("MSXML2.DOMDocument")
xml.preserveWhiteSpace = true
xml.async = false
xml.LoadXML(xmlStr)
If xml.parseError.errorCode <> 0 Then
	Response.Write "Description: " & xml.parseError.reason & "Line: " & xml.parseError.Line
Else
	Dim book, i
	'方法1
	Set book=xml.selectNodes("/books/book")
	For i=0 To book.length-1
		Response.Write book(i).selectSingleNode("name").text&":"&book(i).selectSingleNode("price").text&"<br>"
	Next
	Response.Write "----<br>"
	'方法2
	For i=0 To book.length-1
		Response.Write book(i).selectSingleNode("name").text
		Response.Write book(i).childNodes(1).text&":"&book(i).childNodes(3).text&"<br>"
	Next
	Response.Write "----<br>"
	'方法3
	For i=0 To book.length-1
		Response.Write book(i).getElementsByTagName("name").Item(0).text&":"&book(i).getElementsByTagName("price").Item(0).text&"<br>"
	Next
	Response.Write "----<br>"
	'方法4
	Dim n, p
	Set n=xml.getElementsByTagName("name")
	Set p=xml.getElementsByTagName("price")
	For i=0 To n.length-1
		Response.Write n(i).text&":"&p.item(i).text&"<br>"
	Next
	Response.Write "----<br>"
	'方法5
	Set n=xml.selectNodes("/books/book/name")
	Set p=xml.selectNodes("/books/book/price")
	For i=0 To n.Length-1
		Response.Write n(i).text&":"&p.item(i).text&"<br>"
	Next
End If
Set xml=Nothing
%>
2015-07-31
2024-11-23 星期六 农历十月二十三