I have written a 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 is not giving proper output. Please help me out.
The xml is:
<Product>
<ProductCode>abc</ProductCode>
<ProductName>CC Skye Hinge Bracelet Cuff with Buckle in Black</ProductName>
</Product>
Try this:
<%
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:
Server.MapPath
to resolve virtual pathsselectNodes
and selectSingleNode
instead ofgetElementsByTagName
. The getElementsByTagName
scans all descendants so can return unexpected results and then you always need to index into the results even though you know you expect only one return value.Server.HTMLEncode
data when sending to the response.Here an example how to read your data, given the xml is
<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>
The following 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With