我已经写了代码,在传统的ASP读取XML数据如下:
<%
Dim objxml
Set objxml = Server.CreateObject("Microsoft.XMLDOM")
objxml.async = False
objxml.load ("/abc.in/xml.xml")
set ElemProperty = objxml.getElementsByTagName("Product")
set ElemEN = objxml.getElementsByTagName("Product/ProductCode")
set Elemtown = objxml.getElementsByTagName("Product/ProductName")
set Elemprovince = objxml.getElementsByTagName("Product/ProductPrice")
Response.Write(ElemProperty)
Response.Write(ElemEN)
Response.Write(Elemprovince)
For i=0 To (ElemProperty.length -1)
Response.Write " ProductCode = "
Response.Write(ElemEN)
Response.Write " ProductName = "
Response.Write(Elemtown) & "<br>"
Response.Write " ProductPrice = "
Response.Write(Elemprovince) & "<br>"
next
Set objxml = Nothing
%>
这个代码不给予适当的输出。 请帮助我。
XML是:
<Product>
<ProductCode>abc</ProductCode>
<ProductName>CC Skye Hinge Bracelet Cuff with Buckle in Black</ProductName>
</Product>
试试这个:
<%
Set objXMLDoc = Server.CreateObject("MSXML2.DOMDocument.3.0")
objXMLDoc.async = False
objXMLDoc.load Server.MapPath("/abc.in/xml.xml")
Dim xmlProduct
For Each xmlProduct In objXMLDoc.documentElement.selectNodes("Product")
Dim productCode : productCode = xmlProduct.selectSingleNode("ProductCode").text
Dim productName : productName = xmlProduct.selectSingleNode("ProductName").text
Response.Write Server.HTMLEncode(productCode) & " "
Response.Write Server.HTMLEncode(productName) & "<br>"
Next
%>
笔记:
- 不要使用Microsoft.XMLDOM使用显式MSXML2.DOMDocument.3.0
- 使用
Server.MapPath
解决虚拟路径 - 使用
selectNodes
和selectSingleNode
代替getElementsByTagName
。 的getElementsByTagName
扫描所有后代等都可以返回意外的结果,然后你总是需要索引的结果,即使你知道你希望只有一个返回值。 - 总是
Server.HTMLEncode
发送到响应时的数据。 - 不要把()的怪异的地方,这是没有的VBScript JScript中。
这里的例子,如何给定的XML读取数据,是
<Products>
<Product>
<ProductCode>abc</ProductCode>
<ProductName>CC Skye Hinge Bracelet Cuff with Buckle in Black</ProductName>
</Product>
<Product>
<ProductCode>dfg</ProductCode>
<ProductName>another product</ProductName></Product>
</Products>
下面的脚本
<%
Set objXMLDoc = Server.CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load("xml.xml")
Set Root = objXMLDoc.documentElement
Set NodeList = Root.getElementsByTagName("Product")
For i = 0 to NodeList.length -1
Set ProductCode = objXMLDoc.getElementsByTagName("ProductCode")(i)
Set ProductName = objXMLDoc.getElementsByTagName("ProductName")(i)
Response.Write ProductCode.text & " " & ProductName.text & "<br>"
Next
Set objXMLDoc = Nothing
%>
给
abc CC Skye Hinge Bracelet Cuff with Buckle in Black
dfg another product