XML as Data Source
Written by Amit
Mathur, India on 6th Dec., 2002
Part
1 of 3
Explore the
exciting world of XML !
This is first of a series of 3
articles that I will write to illustrate the use of XML as Data Source. I have divided this tutorial
into 3 chunks. After this tutorial, you will be able to manipulate and play
with XML Data files in the same way as you do with MS Access. In addition to
that, there are certain advantages of using XML, over MS Access. I introduce
these advantages in the text, as we proceed on. The article has been organized
in the increasing order of difficulty.
Section 1
Retrieving XML using ASP
F |
or most of the net based organizations, the data stored in their databases are their sole property. How this data can be organized more effectively and efficiently using XML, is the theme of this article. |
When you create a database in MS Access, even if it is empty, it takes a lot of space just for structure. Right ? Why waste this much space just for structure when you can store information about at least a hundred members of your site in the same space. When you store data as XML, it is stored in the form of a simple text file with the extension .XML, along with a few tags. For the time being, I will not go in the detailed theory of explaining the
intricacies of XML, but rather concentrate on how to access and manipulate it using ASP.
Before we begin, what all is required for your web server to be able to serve XML. For the Server Side XML Processing, IE 5.0+ must be installed on the server. This is because we need XML DOM (XML Document Object Model), which is basically an XML Parser, which is provided as a component of IE5.
Now we are ready to write our scripts. We need two things.
Let us first create a data
source. Suppose we want to maintain a resource repository in which we want to include a brief description of the resource, its link on the web and its link text. The Sample XML data source for this can be:
(Contents of File Resource.XML)
<?xml version="1.0" ?>
<Resource_Repository>
<Resource>
<text>
This program allows you to encrypt your HTML Source Codes so that no one can steal
and Copy Paste them in their own site.
</text>
<link>
<url>
ftp://ftp.cedium.net/internet/htmlcrypt/encryptHTML.exe
</url>
<linetext>
HTML Source Code Encryption
</linetext>
</link>
<Size>
736 KB
</Size>
</Resource>
<Resource>
<text>
DOS Based Eliza Program. Eliza is a Computer program that can talk to you like a human
being. Makes use of Artificial Intelligence.
</text>
<link>
<url>
http://hps.elte.hu/~gk/Eliza/ELIZA.EXE
</url>
<linetext>
Eliza Chatterbot
</linetext>
</link>
<Size>
36 KB
</Size>
</Resource>
</Resource_Repository>
Now we write a script to access this data and display it on the web page. I result will be generated in a very simple format, to make the ASP Code simple to understand.
To begin with, we need to create an XML DOM object on the server. This can be done with a line as simple as :
<% Set objXML = Server.CreateObject("Microsoft.XMLDOM") %>
Now we need to give the path of our data
source. So add the following line to the code:
<%
objXML.Load (Server.MapPath("Resource.xml"))
If objXML.parseError.errorCode <> 0 Then
Response.Write "<p><font color=red>Error loading the Resource file.</font></p>"
Response.End
End If
%>
If the XML DOM Parser throws any error, then we catch that and display the error message.
We want to display the list of all the resources in the file Resource.xml. We know that the resources are enclosed within <Resource> tag. So, the next step is to
create a list of all the objects under the tag <Resource>.
<%
Set objLst = objXML.getElementsByTagName("Resource")
%>
The Length property of object list indicates the
number of items in the list. For example, in our example of Resource.xml, there are two records under the <Resource> tag. So, objLst.Length shows the value 2, when displayed.
<%
Response.write "There are " & objLst.Length & " resources on this site."
%>
This is quite interesting upto now. What about accessing individual sub-items ? Suppose we just want to display the URLs of all the resources in our 'database', how can we do that ?
Create one more object, now referring to the items inside the object list. The
sub-items can be accessed by using childNodes(index). See this code for further understanding :
<%
' for each resource in the list
For i = 0 To objLst.Length - 1
Set subLst = objLst.item(i)
Response.write "<P>" & vbcrlf
Response.Write "<a href='" & subLst.childNodes(1).childNodes(0).Text & "'>" _
& subLst.childNodes(1).childNodes(0).Text & "</a>"
Next
%>
A careful look at the structure of the XML document that we had created earlier reveals that <URL> is inside <Link> which is second element of the <Resource> (first being <text>). If we start our indexing from 0 (Zero), then <Link> is the first element of <Resource> and <URL> is the Zeroeth element inside <Link>. That's why I have written the line:
subLst.childNodes(1).childNodes(0).Text
which is nothing but <URL>. Re-read the previous paragraph if you are still not clear and I am sure you will get it soon.
So, the final source code of the ASP file we have created for displaying the URL of all the resources in our database is:
<%
' creating an object of XMLDOM
Set objXML = Server.CreateObject("Microsoft.XMLDOM")
' Locating our XML database
objXML.Load (Server.MapPath("Resource.xml"))
' checking for error
If objXML.parseError.errorCode <> 0 Then
Response.Write "<p><font color=red>Error loading the Resource file.</font></p>"
Response.End
End If
' referring to Resource
Set objLst = objXML.getElementsByTagName("Resource")
Response.write "There are " & objLst.Length & " resources on this site ."
' for each resource
For i = 0 To objLst.Length - 1
' refer to sub-item
Set subLst = objLst.item(i)
'display the URL
Response.Write "<a href='" & subLst.childNodes(1).childNodes(0).Text & "'>" _
& subLst.childNodes(1).childNodes(0).Text & "</a>"
Next
%>
Of course, you would need to add all those formatting HTML tags to make this list more attractive. But the core remains the same.
Conclusion:
In this article, we learned how to retrieve the 'records' from XML 'database'. For complete Database related operations, we must know how to insert, update and delete the records from the Scripts. In the next article, we will see how to perform these operations as well.
Section 2
Saving Information in XML Files
Using ASP
N |
ow when you
know how to retrieve data from XML files, the next thing you have to
learn is, how to create these XML files from ASP. In this Section
of
the tutorial, I demonstrate how to store data in XML files. |
Advantages of storing data in
XML, as compared to in MS Access are:
-
XML is platform
independent.
You can export your data to Non-Windows OS also.
-
XML data contains semantics
along with it. This means that you can associate a name and property with
data. Further, it is Hierarchical data. So, it gets all those advantages
of storing data in the form of Trees, in-built in it !
-
XML consumes much-much less
space than MS Access data.
-
XML data can be used in EDI
(Electronic Data Interchange). It can also be used in presenting the data
in different formats. Like publishing the same data in PDF, HTML, DOC, PS
... formats.
There are many more advantages
of using XML. Try google to find out more (rather bookish) advantages. That's
not more important for us. We continue with our business - Saving data (or
information, if it really means!) to XML Files.
In this exercise, three files
are involved:
-
HTML Form File
-
ASP Processing Script
-
XML Data File
HTML Form File:
Let us first create the HTML Source file, the easiest of three. The
screen looks something like this.
Add Resource To Database
Sample Data Entry Screen |
The various form field names are
given as: title, url, description, size and Submit, in the top-down order as
shown above.
Now we write an ASP Script, that
will store this data in the XML file. In the current section, we concentrate
on just saving the data in a file. If the file already exists, then it will be
deleted and then again, contents will be written into it. In the next section,
we will see how to append data to an existing file.
So, we proceed further. As done
in previous section, we first create an object of Microsoft.XMLDOM.
<%
Set objXML = server.CreateObject("Microsoft.XMLDOM")
objXML.preserveWhiteSpace = True
%>
Here the second line indicates
that we want to preserve the White Spaces in the file. Now we create the
root element of the document and attach it with the XML document. Look at
the XML document structure given at the beginning of this article, to find
that the root element is Resource_Repository.
<%
Set objRoot = objXML.createElement("Resource_Repository")
objXML.appendChild objRoot
%>
Now we create a new element
and place it under Resource_Repository. A quick glance at the structure
reveals that the direct child of Resource_Repository is Resource. The
immediate child of Resource is <text>, which stores the resource
description. So, three steps are involved in creating a child.
The following code demonstrates
the first and last of above steps.
<%
'Create an element, "Resource".
Set objResource = objXML.createElement("Resource")
' Make <Resource> a child of Root
'
objRoot.appendChild objResource
%>
Now we create another element
<text> which stores the description of the resource. We follow all the 3
steps mentioned earlier in this case. Try to figure them out in the following
code:
<%
'Create a new element, "text". This stor
' es Description of the resource
Set objText = objXML.createElement("text")
' Assign the description to the newly cr
' eated object
objText.Text = Request.Form("description")
' Make Text (description) a child of Res
' ource
objResource.appendChild objText
%>
Easy, isn't it ? Now look at the
following code and observe the symmetry. Please note that this code is written
in accordance with the structure of XML document (Resource.xml) defined at the
start of the article.
<%
' create another child of <Resource>
' ie <link>
Set objLink = objXML.createElement("Link")
' make <link> a child of <Resouce>
'
objResource.appendChild objLink
' create one more element - <url>&nbs;
' p;
Set objUrl = objXML.createElement("url")
' capture URL value from the form and as
' sign it to
' the newly created <url> element
'
objUrl.Text = Request.Form("url")
' make <url> a child of <link>
'
objLink.appendChild objUrl
' create a <linetext> element, assign
' it a value
' and make it a child of <link>
Set objLineText = objXML.createElement("linetext")
objLineText.Text = Request.Form("title")
objLink.appendChild objLineText
' and finally create an element <Size
' > and make
' it a child of <Resource>
Set objSize = objXML.createElement("Size")
objSize.Text = Request.Form("size")
objResource.appendChild objSize
%>
Now we are done with the
structure of the document. The next step is to create a Processing
Instruction (PI) indicating the XML file version, which appears as the
first line of any XML document.
<%
'Create the xml processing instruction.<
' br>
Set objPI = objXML.createProcessingInstruction("xml", "version='1.0'")
'Append the processing instruction to th
' e XML document.
objXML.insertBefore objPI, objXML.childNodes(0)
%>
And as a penultimate step,
save the XML file.
<%
'Save the XML document.
objXML.save strXMLFilePath & "\" & strFileName
%>
Assuming strXMLFilePath
and strFileName to be two variables. And finally, free all the objects.
<%
'Release all of your object references.<
' br>
Set objXML = Nothing
Set objRoot = Nothing
Set objResource = Nothing
Set objText = Nothing
Set objLink = Nothing
Set objUrl = Nothing
Set objLineText = Nothing
Set objSize = Nothing
%>
This concludes our
discussion of saving data to XML files. Before we wrap-up, here is the complete
code, which is well formatted in the form of a function.
<%
'---------------------------------------
' -----------------------------
'The "SaveFormData" Function accepts two
' parameters.
'strXMLFilePath - The physical path wher
' e the XML file will be saved.
'strFileName - The name of the XML file
' that will be saved.
'---------------------------------------
' -----------------------------
Function SaveFormData(strXMLFilePath, strFileName)
'Declare local variables.
Dim objXML
Dim objRoot
Dim objField
Dim objFieldValue
Dim objattID
Dim objattTabOrder
Dim objPI
Dim x
'Instantiate the Microsoft XMLDOM.
Set objXML = server.CreateObject("Microsoft.XMLDOM")
objXML.preserveWhiteSpace = False
'Create your root element and append it
' to the XML document.
Set objRoot = objXML.createElement("Resource_Repository")
objXML.appendChild objRoot
'Create an element, "Resource".
Set objResource = objXML.createElement("Resource")
' Make <Resource> a child of Root
'
objRoot.appendChild objResource
'Create a new element, "text". This stor
' es Description of the resource
Set objText = objXML.createElement("text")
' Assign the description to the newly cr
' eated object
objText.Text = Request.Form("description")
' Make Text (description) a child of Res
' ource
objResource.appendChild objText
' create another child of <Resource>
' ie <link>
Set objLink = objXML.createElement("Link")
' make <link> a child of <Resouce>
'
objResource.appendChild objLink
' create one more element - <url>&nbs;
' p;
Set objUrl = objXML.createElement("url")
' capture URL value from the form and as
' sign it to
' the newly created <url> element
'
objUrl.Text = Request.Form("url")
' make <url> a child of <link>
'
objLink.appendChild objUrl
' create a <linetext> element, assign
' it a value
' and make it a child of <link>
Set objLineText = objXML.createElement("linetext")
objLineText.Text = Request.Form("title")
objLink.appendChild objLineText
' and finally create an element <Size
' > and make
' it a child of <Resource>
Set objSize = objXML.createElement("Size")
objSize.Text = Request.Form("size")
objResource.appendChild objSize
'Create the xml processing instruction.<
' br>
Set objPI = objXML.createProcessingInstruction("xml", "version='1.0'")
'Append the processing instruction to th
' e XML document.
objXML.insertBefore objPI, objXML.childNodes(0)
'Save the XML document.
objXML.save strXMLFilePath & "\" & strFileName
'Release all of your object references.<
' br>
Set objXML = Nothing
Set objRoot = Nothing
Set objResource = Nothing
Set objText = Nothing
Set objLink = Nothing
Set objUrl = Nothing
Set objLineText = Nothing
Set objSize = Nothing
End Function
'Do not break on an error.
On Error Resume Next
'Call the SaveFormData function, passing
' in the physical path to
'save the file to and the name that you
' wish to use for the file.
SaveFormData "C:\Inetpub\wwwroot\save\data","Resource.xml"
'Test to see if an error occurred, if so
' , let the user know.
'Otherwise, tell the user that the opera
' tion was successful.
If err.number <> 0 then
Response.write("Errors occurred while saving data.")
Else
Response.write("<center><h2>Data Entry Successful</h2><P>The resource has been successfully added in the database.</center> ")
End If
%>
Download the file associated
with the article and test the code on your machine. Do not forget to change
the path to which the file has to be saved. (This line has been shown in
strong fonts in above code listing).
Section 3
Appending data to Existing XML Files
I |
n
Section 2, we saw how we can save form data to XML files. But if the
file already existed, then it used to get replaced with the new ones.
Most of the times we want to append data, i.e., add new data to the
existing ones. In this Section of the tutorial, we look at how we can do
so.
|
The major difference between
appending and creating new file is the Processing Instruction (PI) mentioned
in the earlier section. When we append data to an existing file, we do not add
PI to it (obviously, since it is already there!).
So, we first need to check
whether the file already exists. This can be done with the following
simple code:
<%
blnFileExists = objXML.Load(strXMLFilePath & "\" &
strFileName)
%>
If the file already exists, then
we need to set objRoot to the already existing Root element (Resource_Repository).
If the file does not exist, we create a new root element and attach it to XML
document, as we did in Section 2.
<%
'Test to see if the file loaded successf
' ully.
If blnFileExists = True Then
'If the file loaded set the objRoot Obje
' ct equal to the root element 'of the
XML document.
Set objRoot = objXML.documentElement
Else
'Create your root element and append it to the XML document.
Set objRoot = objXML.createElement("Resource_Repository")
objXML.appendChild objRoot
End If
%>
After this we extract the data
from the form and store it in the elements, exactly in the same way as we did
in Section 2. In the end, write the following code:
<%
' Check once again to see if the file lo
' aded successfully. If it did
' not, that means we are creating a new
' document and need to be sure
to
' insert the XML processing instruction.
'
If blnFileExists = False then
'Create the xml processing instruction.&
' nbsp;
Set objPI = objDom.createProcessingInstruction("xml",
"version='1.0'")
'Append the processing instruction to th
' e XML document.
objDom.insertBefore objPI, objDom.childNodes(0)
End If
%>
The complete code for
appending the data is:
<%
'---------------------------------------
' -----------------------------
'The "AppendFormData" Function accepts t
' wo parameters.
'strXMLFilePath - The physical path wher
' e the XML file will be saved.
'strFileName - The name of the XML file
' that will be saved.
'---------------------------------------
' -----------------------------
Function AppendFormData(strXMLFilePath, strFileName)
'Declare local variables.
Dim objXML
Dim objRoot
Dim objField
Dim objFieldValue
Dim objattID
Dim objattTabOrder
Dim objPI
Dim x
'Instantiate the Microsoft XMLDOM.
Set objXML = server.CreateObject("Microsoft.XMLDOM")
objXML.preserveWhiteSpace = False
blnFileExists = objXML.Load(strXMLFilePath & "\" & strFileName)
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
' This part is changed '
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
'Test to see if the file loaded successf
' ully.
If blnFileExists = True Then
'If the file loaded set the objRoot Obje
' ct equal to the root element 'of the XML
' document.
Set objRoot = objXML.documentElement
Else
'Create your root element and append it
' to the XML document.
Set objRoot = objXML.createElement("Resource_Repository")
objXML.appendChild objRoot
End If
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
'Create an element, "Resource".
Set objResource = objXML.createElement("Resource")
' Make <Resource> a child of Root
'
objRoot.appendChild objResource
'Create a new element, "text". This stor
' es Description of the resource
Set objText = objXML.createElement("text")
' Assign the description to the newly cr
' eated object
objText.Text = Request.Form("description")
' Make Text (description) a child of Res
' ource
objResource.appendChild objText
' create another child of <Resource>
' ie <link>
Set objLink = objXML.createElement("Link")
' make <link> a child of <Resouce>
'
objResource.appendChild objLink
' create one more element - <url>&nbs;
' p;
Set objUrl = objXML.createElement("url")
' capture URL value from the form and as
' sign it to
' the newly created <url> element
'
objUrl.Text = Request.Form("url")
' make <url> a child of <link>
'
objLink.appendChild objUrl
' create a <linetext> element, assign
' it a value
' and make it a child of <link>
Set objLineText = objXML.createElement("linetext")
objLineText.Text = Request.Form("title")
objLink.appendChild objLineText
' and finally create an element <Size
' > and make
' it a child of <Resource>
Set objSize = objXML.createElement("Size")
objSize.Text = Request.Form("size")
objResource.appendChild objSize
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
' This part is changed'
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
'Check once again to see if the file loa
' ded successfully. If it did
'not, that means we are creating a new d
' ocument and need to be sure to
'insert the XML processing instruction.<
' br>
If blnFileExists = False then
'Create the xml processing instruction.<
' br>
Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")
'Append the processing instruction to th
' e XML document.
objDom.insertBefore objPI, objDom.childNodes(0)
End If
''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''
'Save the XML document.
objXML.save strXMLFilePath & "\" & strFileName
'Release all of your object references.<
' br>
Set objXML = Nothing
Set objRoot = Nothing
Set objResource = Nothing
Set objText = Nothing
Set objLink = Nothing
Set objUrl = Nothing
Set objLineText = Nothing
Set objSize = Nothing
End Function
'Do not break on an error.
On Error Resume Next
'Call the AppendFormData function, passi
' ng in the physical path to
'save the file to and the name that you
' wish to use for the file.
AppendFormData "C:\Inetpub\wwwroot\append\data","Resource.xml"
'Test to see if an error occurred, if so
' , let the user know.
'Otherwise, tell the user that the opera
' tion was successful.
If err.number <> 0 then
Response.write("Errors occurred while saving data.")
Else
Response.write("<center><h2>Data Entry Successful</h2><P>The resource has been successfully added in the database.</center> ")
End If
%>
Hope you enjoyed this article.
But this is still not over. XMLDOM contains rich set of functions and some of
them are very amazing. I will continue to write on this series. Explore this
whole new world of XML. This is really exciting !
(I am in the Final Year of my B.E. in
Computer Engineering and my Final Year project is development of a Complete
Database Management System (DBMS) for storing and manipulating XML and a new
query language XQL much like XQuery, which will be used to query XML data just
as we today use SQL for RDBMS.)
In the end, visit my two web
sites and I hope you will like both of them:
-
http://www.vyomworld.com
: This contains a huge source code library, 100's of Placement Papers of
companies world wide, GRE Antonym test of 1208 Questions, GRE Word List,
Search Engine and Free Professional Certification.
-
http://amitmathur.8m.com
: This contains eBooks on Compiler Programming, Virus Programming,
Online tests on C++, Java, Computer Fundamentals, Sybase, etc, TSR
Articles, Discussion Forum, my resume, numerous articles written by me on
hacking and IP Addressing and some contributions by the visitors and their
comments.
Comments, Suggestions,
Criticism ? Mail me directly from the web page: http://amitmathur.8m.com/mailme.html
If you have some really exciting ASP Scripts and want to host them on
an ASP server free of cost without ADs, contact
me and I will host them free for you on my
website. Keep writing good and original scripts.
Thanks.
Please vote
and support this effort.