Recuperando XML usando o ASP
|
F ou a maioria das organizações baseadas líquidas, os dados armazenados em suas bases de dados são sua única propriedade. Como estes dados podem ser organizados mais eficazmente e eficientemente usando XML, é o tema deste artigo.
|
Quando você cría uma base de dados no acesso do ms, mesmo se estiver vazio, faz exame de muitos do espaço apenas para a estrutura. Direita? Porque desperdício este muito espaço apenas para a estrutura quando você puder armazenar a informação aproximadamente pelo menos cem membros de seu local no mesmo espaço. Quando você armazena dados como XML, está armazenado no formulário de uma lima de texto simples com a extensão .XML, junto com alguns Tag. Por o tempo que é, eu não irei na teoria detalhada de explicar os intricacies de XML, mas concentro rather em como alcançá-la e manipular que usa o ASP.
|
Antes que nós comecemos, o que tudo está requerido para seu web server servem a XML. Para o lado XML do usuário que processa, o IE 5.0+ deve ser instalado no usuário. Este é porque nós necessitamos XML DOM (modelo do objeto do original de XML), que é bàsicamente um Parser de XML, que é fornecido como um componente de IE5.
|
Agora nós estamos prontos para escrever nossos certificados. Nós necessitamos duas coisas.
|
- Origem dos dados
- Certificado do ASP para manipular os dados.
|
Deixar-nos primeiramente criar uma origem dos dados. Supôr que nós queremos manter um repositório do recurso em que nós queremos incluir uma descrição breve do recurso, sua ligação na correia fotorreceptora e seu texto da ligação. A origem dos dados da amostra XML para esta pode ser:
|
(Índices da lima 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.
|