我在经典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 - 使用经典 ASP 读取 xml 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522316/