Everywhere you look now you will find references to XML as the savior of the Internet. In this section, we will look at how we can use Microsoft Access 2002 to both import and export XML files. First we will have a quick overview of what XML is and why it is so useful. For a detailed look at XML, see Beginning XML 2nd Edition , from Wrox Press (ISBN 1-861005-59-8).
XML is a markup language very similar to HTML in that it uses a set of tags that permit you to work with structured data. With HTML you are restricted to using the tags that comprise the language. This restriction does not apply when using XML as you can create any tags you like. First let's take a look at a simple XML file exported from within the Ice Cream database. Note that this file is incomplete:
<?xml version="1.0" encoding="UTF-8"?> <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="companyxml.xsd"> <tblCompany> <CompanyID>1</CompanyID> <CompanyName><![CDATA[Fran and Nick's Fruit and Nuts]]></CompanyName> <Address>37 Walnut Grove</Address> <City>Nutbush</City> <State>Tennessee</State> <ZipCode>38053</ZipCode> <Country>USA</Country> <Phone>(423) 935 9032</Phone> <Fax>(423) 935 9001</Fax> <Supplier>1</Supplier> </tblCompany> <tblCompany> <CompanyID>2</CompanyID> ...
The above XML file is simply a copy of the Customers table. When
It is important to note that this is a raw XML file which has not been formatted manually. The XML file is using the default format template supplied by Internet Explorer which
As you can see this is similar to HTML and tags are used to layout the page. Note the minus signs to the left of the page. Clicking the symbol will contract the tree, changing the symbol to a plus sign. Clicking the plus sign has the
Properly formatted XML is said to be well-
An XML declaration must be the first line in the file.
All XML tags must have an opening and a closing tag.
Tags cannot contain comments.
Tags are case-sensitive.
All elements must be properly nested.
All documents must have a root tag. This is the first tag in the document.
So why bother - what are the advantages to using XML in the first place? Before looking at some XML examples, let's have a quick overview of the advantages of XML.
You can define your own XML tags to suit your purpose. For example, the following is a valid XML fragment :
<Person> <Type>Male</Type> <height>Big</height> <Hair>Black</Hair> <eyes>blue</eyes> </Person>
Many databases can actually store XML documents (Oracle, DB2, SQL Server).
XML is an
It is widely used in business to transfer data. For example, a form of XML has been used by the press industry to exchange news information for many
Permits different systems to
Designed for the Internet.
Has a very small footprint in the browser.
Separates content and appearance.
Exporting a table to XML is a simple process, and at this level very little about XML needs to be known. Let's see how to export the Customer table as XML. Firstly, in the Database window select tblCompany . With the table highlighted:
Click on File on the main Access menu
Select File Export
In the Export Table dialog use the Save As Type drop-down list and select XML Documents
Note that Access will add the table name to the dialog as the default file
Click the Export button
Now this is where things get interesting. We are given a few different ways that we can export the data as XML:
Schema of the data
This option will create a simple XML file containing only the table data, as shown in the screenshot below:
This form of XML export uses the default presentation template in Internet Explorer to display the data in a tree structure. If you also select the Presentation of your data checkbox:
Then you also generate an XSL and HTML file. This option is available only if the Data checkbox is selected. The XSL file is much like a HTML template and controls the presentation of your XML data. Rather than use the default template in IE the browser will use the defined XSL file to present your data.
XSL can be compared to a Cascading Style Sheet used with HTML and deals only with the layout and presentation of the data contained in your XML file in a process called transformation. Without your own XSL file, the XML file will be displayed using the browser default.
This option permits you to export the structure or Schema of the table instead of the data. You may export both the schema and the data in a single operation by checking the
Schema of the data
boxes in the
dialog. If you want to select
Schema of data
only, you can then import the resulting file back to Access or SQL Server 2000 Desktop (which is provided free of charge on the Office XP CD-ROM) and have an unpopulated copy of the company table. The XML schema file contains the structure of your Access table including data types, indexes, field
Clicking on the Advanced button will close the initial XML dialog and open a new dialog. This gives you several additional options when exporting. For example, when exporting a schema you can choose to Include primary key and index information from the file. Note that once you open the advanced dialog you will be unable to return to the initial export screen. The advanced dialog also permits you to include the schema information within the XML file rather than as a distinct document.
It is also possible to use VBA to import and export data as XML. There are two new
Open a new module and enter the following code into the module window:
Sub ExportcustXML() Application.ExportXML ObjectType:=acExportTable, _ DataSource:="tblCompany", _ DataTarget:="c:\Companyxml.xml", _ SchemaTarget:="CompanySchema.xml", _ OtherFlags:=1 End Sub
This procedure will export the Customers table as XML. The resulting file CompanyXML.xml will be saved to C:\ or any folder specified within the argument. In addition, we are also creating a schema file, CompanySchema.xsl . The OtherFlags option, currently set to one offers you additional control over the way the file is exported.
Will include any
Creates relational properties
Creates an ASP wrapper as opposed to a HTML wrapper
Creates extended schema properties
Creating a generic procedure:
We can also create a nice simple generic procedure for exporting objects as
Sub ExportXML (tabl As String, path As String) Application.ExportXML ObjectType:=acExportTable, _ DataSource:=tabl, DataTarget:=path End Sub
This procedure automates the manual example just seen, and provides you with more flexibility when it is called. The resulting file will look no different to that produced manually. Importing an XML file is just as easy.
Before we import an XML file using ADO, we need to export a new copy. We will discuss the reasons for this shortly.
In the Database Window, select tblCompany
From the main menu select File Export
Select XML Documents from the Save As Type dialog, accepting the default name for the file
Save the file to C:\
In the dialog, accept the default option of Data and Schema of the data , and click OK to finish the export
Open a new module and enter the procedure shown below:
Sub ImportXML() Application.ImportXML "C:\tblCompany.xml" End Sub
This procedure will create a perfect copy of the customer table which already exists within the database. In this case, the table name will be suffixed with the number 1. Each time you run the procedure the table will be recreated as tblcustomer2 , tblcustomers3 , and so on. In addition, there are three arguments available when using ImportXML :
acStructureAndData , which creates the table and populates it with data
acStructureOnly , creates the table structure only
acAppendData , will simply append the XML data to an existing table
OK, so why did we not use the XML file we created earlier via ADO? Well try it and see what happens, you can't import it. ADO creates a type of XML file that is not recognized by Microsoft Access. Access 2002 uses a specific type of XML called
As with ExportXML we can also create a simple generic procedure which can be used to import XML files.
Sub ImportXML(path As String) Application.ImportXML DataSource:=path, _ ImportOptions:=acStructureAndData End Sub
In this case all that is required is the full path to the XML file being imported.
In order to execute the above procedure, open the Immediate window while in the VBE. Press Ctrl + G or select View Intermediate Window using the main menu option. We will import the XML file created in the example above. Simply enter the following into the Immediate window:
Return to the database window and notice that a new tblCompany has been created based on the XML file. If you have been testing, you should notice that the table name is followed by a number.
As you can see Access 2002 offers several ways to use XML within a database. In these brief examples we have exported data to XML and then imported an XML file back into Microsoft Access. But what's the point in it all? Well as we seen above, when we
When you need to have reports available via the Internet, XML offers you another tool in the arsenal. Similar to how we can save reports as DAPs, it is also possible to save reports as XML files via the Access interface. In this way we can, again, make data available via the Internet. For static data, we provide a link to the XML file as opposed to a connection to the database. However, remember that the data is static and the
The process used to export a report to XML is identical to that used with a table: select the report, right-click, and choose Export . However, in this case, you will return a variety of documents including a HTML file, the XML File and an XSL stylesheet. Generally to view the data you select the HTML file which acts as the template for the other file groups.
Select the Ingredients report from the Database window
Select File Export from the main menu
Select XML Documents from the Save as type list
Click the Export button
Accept the default Data in the Export XML dialog
Navigate to the folder you saved the files to, and open Ingredients.html using a web browser
Notice that we are opening a HTML file, not the XML directly. The HTML file contains a script which calls the required XML and XSL files for viewing. The relevant lines are show as bold in the script below.
SCRIPT event=onload for=window> objData = new ActiveXObject("MSXML.DOMDocument"); objData.async = false; objData.load("Ingredients.xml"); if (objData.parseError.errorCode != 0) alert(objData.parseError.reason); objStyle = new ActiveXObject("MSXML.DOMDocument"); objStyle.async = false; objStyle.load("Ingredients.xsl"); if (objStyle.parseError.errorCode != 0) alert(objStyle.parseError.reason); document.open("text/html","replace"); document.write(objData.transformNode(objStyle));
Publishing live data to the Internet means that every time the web page is viewed, the data is
To use Active Server Pages (ASP) you will need either Microsoft Internet Information Server (IIS) or Microsoft Personal Web Server. IIS5 is available with Windows 2000 Server and Windows XP Professional. Microsoft Personal Web Server may be used for testing and development purposes only, if required. Many developers who have moved onto Windows 2000 and XP Professional operating systems have the advantage in that a full version of IIS is available for use when working with the web. That being the case, Personal Web Server may not be available on your machine and you will use IIS.
Just for information ASP is also available for Unix using a third party product. Details are available at
. It has also been
The following example requires the use of an ODBC System DSN and an IIS Virtual Directory . To keep this chapter focused, we've included this information as an Appendix on the CD, for those of you that are not familiar with this.Please also ensure that you have both IIS and MDAC 2.7 installed on your machine before you attempt this example.
In the Tables window of the example database, select tblIceCream
Select File Export from the main menu
From the Export dialog change the Save as type to Microsoft Active Server Pages
Save the file in a folder below your C:\Inetpub\wwwRoot directory (if this directory doesn't appear, you probably don't have IIS installed correctly - see the appendices)
Press the Export button to open the ASP Options dialog:
Since the data is updated every time the ASP page is loaded, you need to fill in some details:
If you've got an HTML template you can enter its name here. This can help give your ASP pages a consistent look.
Data Source Name
This can be an ODBC DSN (as shown) or ADO connection string. ADO is discussed in Chapter 21. This is how the ASP page connects to the Access database to get the data.
User and Password
If you have security set on your Access database you should enter a user name and password here,
This allows you to enter the default URL of the web server that will host this page. Unlike HTML pages, which can be viewed directly by a browser, an ASP file must be
After entering a DSN and the server URL shown in the above figure, you can view the web page by opening it in a web browser. In the case of this example, we have created a folder on the web server called BegVBA . The example file is placed in there. The URL localhost is the common URL used to specify the server running on the development machine. If you save the file in a folder other than BegVBA remember to use that folder name.
Enter the URL: http://localhost/BegVBA/tblIceCream.asp
This looks pretty similar to the previous static example, but this time the data will be fetched from the database every time the web page is viewed. In order to actually see the changes you will need to amend one of the records in the table. In this case, we have added some text to the Walnut Wonder record, but you can alter any record that you choose.
When you're done, hit the Refresh button in your browser. See how the changes you've just made are carried across.
Notice how the new data is visible immediately. You don't have to export this again, because each time this web page is viewed, the data is fetched directly from the database. Again for completeness a fragment of the ASP script taken from the above file is shown below. Note the use of the <
<% If IsObject(Session("ice_conn")) Then Set conn = Session("ice_conn") Else Set conn = Server.CreateObject("ADODB.Connection") conn.open "ice","","" Set Session("??ice_conn") = conn End If %> <% If IsObject(Session("tblCompany_rs")) Then Set rs = Session("tblCompany_rs") Else sql = "SELECT * FROM [tblCompany]" Set rs = Server.CreateObject("ADODB.Recordset") rs.Open sql, conn, 3, 3 If rs.eof Then rs.AddNew End If Set Session("tblCompany_rs") = rs End If %>