Parsing XML File in ASP


Hi If you need to parse a XML file in ASP Code you may use the following:

First we need a XML file named book.xml.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<books>
<book>
<name>
<![CDATA[ ASP and AJAX  ]]>
  </name>
<description>
<![CDATA[ This is a book for ASP and AJAX ]]>
  </description>
<author>
<![CDATA[ Author 1 ]]>
  </author>
  </book>
<book>
<name>
<![CDATA[ XML ]]>
  </name>
<description>
<![CDATA[This book is for XML learning  ]]>
  </description>
<author>
<![CDATA[ Author 2 ]]>
  </author>
  </book>
  </books>
  </configuration>
Now create a ASP file to parse this XML.
<%
‘Set the XML Object
 

Set objXML = Server.CreateObject(“Microsoft.XMLDOM”)

‘Set Asynchoronous = false
objXML.async = False

‘Load the XML file.
‘User Server.MapPath method is the XML is located in your site.
‘Else you can use the absolute path.

objXML.Load (Server.MapPath(“db/book.xml”))

‘If there is any errors pasring the file the notify

If objXML.parseError.errorCode 0 Then

Response.Write “Error Parsing XML”

Response.Write  “Rason :” & objXML.parseError.reason & “Error Line: ” & objXML.parseError.line

End If

‘Get ALL the Elements by the tag name book

Set books = objXML.getElementsByTagName(“book”)

‘Now Iterate through the List and Display

 For i = 0 to (books.Length-1)
    Response.Write “Name: ” & books.item(i).childNodes(0).text  & “<br/>”
    Response.Write “Description: ” & books.item(i).childNodes(1).text & “<br/>”
    Response.Write “Author: ” & books.item(i).childNodes(2).text & “<br/>”
Next
%>

Bingo 😉