阅读使用传统的ASP XML数据(Reading xml data using classic AS

2019-07-30 11:46发布

我已经写了代码,在传统的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>

Answer 1:

试试这个:

<%   

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解决虚拟路径
  • 使用selectNodesselectSingleNode代替getElementsByTagName 。 的getElementsByTagName扫描所有后代等都可以返回意外的结果,然后你总是需要索引的结果,即使你知道你希望只有一个返回值。
  • 总是Server.HTMLEncode发送到响应时的数据。
  • 不要把()的怪异的地方,这是没有的VBScript JScript中。


Answer 2:

这里的例子,如何给定的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


文章来源: Reading xml data using classic ASP