从技术上来说,在ASP环境中,读入并管理XML文本的主要方法有三种:
创建MSXML对象,并且将XML文档载入DOM;
使用服务器端嵌入(Server-Side Include,SSI);
就如同访问其他文本文件一样,使用FileSystemObject来访问XML文档;
第四种方法是在客户端创建内置的数据岛,有关的内容以后讲解。
一、使用DOM
为了在ASP代码中使用DOM,需要创建一个Microsoft XML分析器的实例,它像任何别的COM组件一样被实例化,在页面的开始处顼要增加几行标准代码。这些代码创建一个分析器实例,加载XML文档至DOM,并且将根元素(即文档元素)设置为当前节点。
‘Instatiate the XML Processor
Set objXML = Server.CreateObject(“Microsoft.XMLDOM”)
Load the XML Document
objXML.load(Server.MapPath(“mydata.xml”)
Set the Document Element
Set objRootElement = objXML.documentElement
在XML文档被加载之前,还需要执行第四步,即设置validateOnParse属性为True,这可确保被加载的文档为有效的XML文档。这可避免后面遇到的各种麻烦:
Instatiate the XML Processor
Set objXML = Server.CreateObject(“Microsoft.XMLDOM”)
The processos should validate the document
objXML.validateOnParse = True
Load the XML Document
objXML.load(Server.MapPath(“mydata.xml”)
Set the Document Element
Set objRootElement = objXML.documentElement
最后,还有一个可选步骤,它也是出现在加载之前。它要求同步加载文件:
objXML.async = false
这说时加载并验证一个相当大的文件需要占用一些时间。另一种替换方案是忽略这一步,允许非同步加载,这是缺省情况,一旦完成这些初始化步骤,XML文档就被加载,并且做好了被处理的准备。DOM所有重要的功能都是可配置的。
当然,就如同任何COM对象一样,在使用完之后,请记住必须销毁它:
Set objXML = nothing
二、服务器端嵌入
服务器端嵌入可用于将XML文档代码插入ASP页面。
三、用ASP代码处理XML的示例




<%
Dim sourceFile,source,rootElement,HTMLCode
sourceFile = Request.ServerVariables(“APPL_PHYSICAL_PATH”) & “xml\contacts.xml”
set source = Server.CreateObject(“Microsoft.XMLDOM”)
source.async = false
source.load sourceFile
set rootElement = source.documentElement
HTMLCode = HTMLCode & “”
HTMLCode = HTMLCode & rootElement.childNodes(0).text
HTMLCode = HTMLCode & “


HTMLCode = HTMLCode & rootElement.childNodes(0).text
HTMLCode = HTMLCode & “


HTMLCode = HTMLCode & rootElement.childNodes(0).text
HTMLCode = HTMLCode & “


response.write(HTMLCode)
set source = nothing
%>


contacts.xml



JOHN
111-1111-111


SMITH
222-2222-222


MIKE
333-3333-333


经XSL格式化的XML数据
styleContact.asp


<%
sourceFile = server.mapPath(“contact.xml”)
styleFile = server.mapPath(“contact.xsl”)
set source = Server.CreateObject(“Microsoft.XMLDOM”)
source.async = False
source.load(sourceFile)
set style = Server.CreateObject(“Microsoft.XMLDOM”)
style.async = False
style.load(styleFile)
response.write(source.transformNode(style))
%>


contact.xml




ZHOU.ZF
11111111111


LISTEN
22222222222


BUBU
33333333333


contact.xsl












12下一页阅读全文