Retrieving XML with ASP

Illustrates a way to deal with XML data through ASP DOM.

<%
'xml serverside
xmlURL = "places.xml"

set xmlDoc = Server.CreateObject("Msxml2.DOMDocument")
xmlDoc.async = false
xmlDoc.setProperty "ServerHTTPRequest", True
xmlDoc.load(xmlURL)

If xmlDoc.parseError.errorCode <> 0 Then
  response.write xmlDoc.parseError.reason
else
  'This retrieves the content of the element "map_url"
  response.write xmlDoc.getElementsByTagName("map_url")(0).childNodes(0).nodeValue
end if

set xmlDoc = Nothing %>

The way to show an element above is a nice way to access one directly, just change the numbers to access the first, second, third, etc. If you have a structure that looks something like this:
<parent name="daddy">
<kid>1</kid>
<kid>2</kid>
<kid>3</kid>
</parent> 

Then you should be able to access the code with something like this:
 'Access property name of parent tag:
response.write xmlDoc.getElementsByTagName("parent")(0).getAttribute("name")

'Access all the kids:
kid_collection = xmlDoc.getElementsByTagName("parent")
response.write "First kid :" & kid_collection(0).firstChild.nodeValue
response.write "Second kid :" & kid_collection(1).firstChild.nodeValue
response.write "Third kid :" & kid_collection(2).firstChild.nodeValue

'If the kids had any attributes, you could have accessed them like this:
response.write "First kid :" & kid_collection(0).getAttribute("name")
response.write "Second kid :" & kid_collection(1).getAttribute("name")
response.write "Third kid :" & kid_collection(2).getAttribute("name") 

This should cover some of the basic ground to get started.

Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0