7

我已经编写了一个用于在经典 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>
4

2 回答 2

11

试试这个:

<%   

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解析虚拟路径
  • 使用selectNodesandselectSingleNode而不是getElementsByTagName. 扫描所有后代,getElementsByTagName因此可以返回意外结果,然后您始终需要对结果进行索引,即使您知道您只需要一个返回值。
  • Server.HTMLEncode发送到响应时总是数据。
  • 不要把 ( ) 放在奇怪的地方,这是 VBScript 而不是 JScript。
于 2012-07-17T20:58:40.167 回答
4

这是一个如何读取数据的示例,假设 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
于 2012-07-17T16:14:20.363 回答