Reading xml data using classic ASP

I wrote code for reading xml data in classic asp as follows:

<% 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 %> 

This code does not give the correct output. Please help me.

xml:

 <Product> <ProductCode>abc</ProductCode> <ProductName>CC Skye Hinge Bracelet Cuff with Buckle in Black</ProductName> </Product> 
+7
source share
2 answers

Try the following:

 <% 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 %> 

Notes:

  • Do not use Microsoft.XMLDOM using explicit MSXML2.DOMDocument.3.0
  • Use Server.MapPath to resolve virtual paths
  • Use selectNodes and selectSingleNode instead of getElementsByTagName . getElementsByTagName scans all descendants, so it can return unexpected results, and you always need to index the results, even if you know you expect only one return value.
  • Always Server.HTMLEncode data when sending a response.
  • Do not put () in weird places, this is VBScript, not JScript.
+10
source

Here is an example of how to read your data, given 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> 

Next script

 <% 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 %> 

gives

 abc CC Skye Hinge Bracelet Cuff with Buckle in Black dfg another product 
+4
source

All Articles