In a related article on importing into MS Access 2003 from an external source using its built-in support for such an activity, we fell short of a complete success unless some styling/schema information could be supplied. This tutorial looks at the reverse process, namely exporting data from MS Access into XML format.
This article is about exporting XML data from MS Access 2003. XML is the lingua franca of the Internet and is used extensively in how we communicate. XML is ubiquitous and will become more so with time. The extensibility, the essentially text-based format, and the ability to carry the data in its body make it unique, and extremely useful in how information is disseminated.
MS Access has gone through many revisions, and over time it has added support for importing and exporting its data into HTML as well as XML. One look at the source view of the Data Access Pages, a new object to display data on the intranet which appeared in version 2000 and above, reveals how deeply these different formats have penetrated the product. According to the product document, MS Access 2003 fully supports importing and exporting XML. In addition to the built-in support explored in this article, and the previous one dealing with importing, one could also use scripting support to explore this functionality in MS Access 2003. But this is not considered in this tutorial.
Exporting a single table from MS Access
The exported table
A new table named Argentina was constructed from the Orders table in the Northwind example database. This is a table that shows all orders originating from Argentina. The contents of this table are shown in the next picture.
The next picture shows the design view of the table. It has only four fields.
The Export drop-down menu item can be accessed from the File menu item. Highlighting the Argentina table and clicking on the Export drop-down pops up the window shown in the next picture. By default, it opens up the My Documents folder to save the export to one of several MS Access database file extensions. Since we would like to host it on the intranet, the location shown in the next picture is chosen. Since the XML format is the preferred format, this choice is also made as shown. Additionally a name for the file is needed, herein AccXml.xml was used.
Clicking on the Export button now brings up the window Export XML shown in the next picture. Well, there is more to exporting than simply producing a single file. The default export takes in the Data (XML) as well as Schema of the Data (XSD). Additionally the Presentation of your data (XSL), an extensible style language resulting in the XSL file, may also be chosen. This is not all; there is more as indicated by the More Options... button. We will take that up in another tutorial.
For now, accept the default and click OK. This does not give any message as to what happened, but sure enough, you will find the two files AccXml.xml and AccXml.xsd as shown in the next picture in the root directory of the IIS default web site.
The content of the AccXml.xml file is shown in the next paragraph, after removing all but one of the 'customers' to make the screen display shorter.
AccXml.xml (Generated using XML and XSD combination)
It is a well formed document with reference to the standards of the W3C as well as to Microsoft's Office data structures (shown highlighted). The schema instance has two attributes: where the schema may be found, and the schema generated date and time. The data content is now enclosed in a root <dataroot..../>(in blue). This also happens to be the MS Access preferred format of an XML file that can be successfully imported. The AccXml.xsd which is also in XML format is shown in the next paragraph.
This schema will not be described in detail as it is somewhat outside the scope of this tutorial, but suffice it to say that the generated XML file fully conforms with this schema. It details the data root, the nodes and the child nodes, as well as the data type and data size, as you may infer with reference to the original table. It also refers to the "Office data," the link that binds all Office products. Now that the XML file is available on the intranet, it will be interesting to see how the display will come out in the browser. The next picture shows a truncated portion.
XML by itself produces a poor display, but together with an associated XSL file, it can display in several different formats. By reverting back to an earlier step, the XSL can also be exported by checking the appropriate options. However, the Data box must must be checked as well, as you can see what happens if Data is not selected as shown in the next picture.
Choosing Data (XML) and the Presentation of your data (XSL) and clicking the OK button creates these files (XML and XSL) in the chosen directory. Since the AccXml.xml already exists, it is overwritten if you choose to do so, as in the present case. Additionally it also creates an AccXml.htm page as well. There are differences to the AccXml.xml file depending on whether you choose the schema or the style generation, as you can see from the next picture, which shows the AccXml.xml generated by choosing the Data (XML)& Style (XSL) combination.
AccXml.xml (Generated using XML and XSL combination)
<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata"
generated="2006-06-29T11:00:57">
<Argentina>
<CustomerID>OCEAN</CustomerID>
<OrderDate>1997-01-09T00:00:00</OrderDate>
<RequiredDate>1997-02-06T00:00:00</RequiredDate>
<ShipName>Océano Atlántico Ltda.</ShipName>
</Argentina>
<!--Only one customer included in this picture-->
</dataroot>
The generated AccXml.htm file when browsed is displayed as shown in the next picture. Gone are the tags, and the node tree. This is now formatted into a table, drab no doubt, but still a no-frills HTML display.
Th next paragraph shows the details of the AccXml.xsl file generated with the above XML file. This is the file that transforms the XML data for presentation.
xmlns:fx="#fx-functions" exclude-result-prefixes="msxsl fx">
<xsl:output method="html" version="4.0" indent="yes"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>
<xsl:template match="//dataroot"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<html>
<head>
<META HTTP-EQUIV="Content-Type"
CONTENT="text/html;charset=UTF-8"/>
<title>Argentina</title>
<style type="text/css"></style>
</head>
<body link="#0000ff" vlink="#800080">
<table border="1" bgcolor="#ffffff"
cellspacing="0" cellpadding="0" id="CTRL1">
<colgroup>
<col style="WIDTH: 0.9375in"/>
<col style="TEXT-ALIGN: right; WIDTH: 0.9375in"/>
<col style="TEXT-ALIGN: right; WIDTH: 0.9375in"/>
<col style="WIDTH: 0.9375in"/>
</colgroup>
<tbody>
<tr>
<td>
<div align="center">
<strong>CustomerID</strong>
</div>
</td>
<td>
<div align="center">
<strong>OrderDate</strong>
</div>
</td>
<td>
<div align="center">
<strong>RequiredDate</strong>
</div>
</td>
<td>
<div align="center">
<strong>ShipName</strong>
</div>
</td>
</tr>
</tbody>
<tbody id="CTRL2">
<xsl:for-each select="Argentina">
<!-- Cache the current node in case the a field is
formatted -->
<xsl:value-of select="fx:CacheCurrentNode(.)"/>
<tr>
<td>
<xsl:value-of select="CustomerID"/>
</td>
<td>
<xsl:value-of
select="fx:FormatFromXSL('OrderDate', '', '', '', 7)"/>
</td>
<td>
<xsl:value-of
select="fx:FormatFromXSL('RequiredDate', '', '', '', 7)"/>
</td>
<td>
<xsl:value-of select="ShipName"/>
</td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
<msxsl:script language="VBScript" implements-prefix="fx"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"><![CDATA[
Option Explicit
' *******************************************************************
' ** Functions dynamically generated to evaluate expressions used as
a Control Source
' *******************************************************************
' *************************************************************
' ** Functions dynamically generated to evaluate running sums
' *************************************************************
' This function will calculate the running sums and expressions for the
Detail section
Function CalculateExpressions_Detail(CurrentNode, GroupNodes)
PrepExpressions CurrentNode, GroupNodes
On Error Resume Next
CalculateExpressions_Detail = ""
End Function
' This function will calculate the running sums and expressions for the
Global section
Function CalculateExpressions_Global(CurrentNode, GroupNodes)
PrepExpressions CurrentNode, GroupNodes
On Error Resume Next
CalculateExpressions_Global = ""
End Function
' *********************************************************************
' **Functions dynamically generated to be used for sorting and grouping
' *********************************************************************
' ************************************************
' ** Code staticly copied for expressions to use
' ***********************************************
'variable declaration
Dim objCurrNode
Dim objCurrNodeT
Dim cGroupCount
Dim objGroupNodes
Set objGroupNodes = Nothing
Set objCurrNode = Nothing
cGroupCount = 0
Function PrepExpressions(CurrentNode, GroupNodes)
CacheCurrentNode CurrentNode
CacheGroupNodes GroupNodes
PrepExpressions = ""
End Function
Function CacheCurrentNode(objNodeList)
Set objCurrNode = objNodeList.item(0)
CacheCurrentNode = ""
End Function
Function CacheGroupNodes(objNodeList)
Set objGroupNodes = objNodeList
cGroupCount = objGroupNodes.length
CacheGroupNodes = ""
End Function
Function GroupValue_quarter(strValue)
GroupValue_quarter = Left(strValue, 4) &
DatePart("q", BuildDateFromStr(strValue, False))
End Function
Function GroupValue_week(strValue)
GroupValue_week = Left(strValue, 4) &
DatePart("ww", BuildDateFromStr(strValue, False))
End Function
Function GroupValue_interval(nValue, nInterval)
GroupValue_interval = Int(nValue / nInterval)
End Function
Function Page()
Page = 1
End Function
Function Pages()
Pages = 1
End Function
Function ToString(varValue)
On Error Resume Next
ToString = ""
ToString = CStr(varValue)
End Function
Function ToNumber(varValue)
On Error Resume Next
ToNumber = 0
ToNumber = CDbl(varValue)
End Function
Function FormatFromXSL(strRef, strFormat, iNumDecimals, LCID, nType)
FormatFromXSL = ToString(Format(GetValue(strRef, nType),
strFormat, iNumDecimals, LCID, nType))
End Function
Function Format(varValue, strFormat, iNumDecimals, LCID, nType)
Dim FormatTemp
Dim strTemp
If IsDate(varValue) Then
Select Case strFormat
Case "General Date"
FormatTemp = FormatDateTime(varValue, vbGeneralDate)
Case "Long Date"
FormatTemp = FormatDateTime(varValue, vbLongDate)
Case "Medium Date"
FormatTemp = Day(varValue) & "-" & MonthName
(Month(varValue), True) & "-" & Mid(Year(varValue), 3, 2)
Case "Short Date"
FormatTemp = FormatDateTime(varValue, vbShortDate)
Case "Long Time"
FormatTemp = FormatDateTime(varValue, vbLongTime)
Case "Medium Time"
strTemp = FormatDateTime(varValue, vbLongTime)
If (IsNumeric(Mid(strTemp, 2, 1))) Then
FormatTemp = Mid(strTemp,1,5) & Mid(strTemp, 9)
Else
FormatTemp = Mid(strTemp,1,4) & Mid(strTemp, 9)
End If
Case "Short Time"
FormatTemp = FormatDateTime(varValue, vbShortTime)
Case Else
Select Case LCase(strFormat)
Case "yyyy", "q", "m", "y", "d", "w", "ww", "h", "n", "s"
FormatTemp = DatePart(LCase(strFormat), varValue)
Case Else
' This does not currently support custom formats such
as dd-mmm-yyyy
FormatTemp = FormatDateTime(varValue, vbGeneralDate)
End Select
End Select
ElseIf IsNumeric(varValue) Then
Select Case strFormat
Case "General Number"
FormatTemp = varValue
Case "Currency"
FormatTemp = FormatCurrencyPerLocale(varValue,
iNumDecimals, LCID)
Case "Euro"
' This does not really support the Euro format.
FormatTemp = FormatCurrencyPerLocale(varValue,
iNumDecimals, LCID)
Case "Fixed"
If IsNumeric(iNumDecimals) Then
FormatTemp =
FormatNumber(varValue, iNumDecimals, vbTrue, vbUseDefault, vbFalse)
Else
FormatTemp =
FormatNumber(varValue, 2, vbTrue, vbUseDefault, vbFalse)
End If
Case "Standard"
If IsNumeric(iNumDecimals) Then
FormatTemp =
FormatNumber(varValue, iNumDecimals, vbUseDefault, vbUseDefault, vbTrue)
Else
FormatTemp =
FormatNumber(varValue, 2, vbUseDefault, vbUseDefault, vbTrue)
End If
Case "Percent"
If IsNumeric(iNumDecimals) Then
FormatTemp = FormatPercent(varValue, iNumDecimals)
Else
FormatTemp = FormatPercent(varValue)
End If
Case "Scientific"
Dim nExp
Dim nValue
If (varValue = 0) Then
nExp = 0
Else
nExp = Int(Log(Abs(varValue)) / Log(10))
End If
nValue = Round(CDbl(varValue)/(10^CDbl(nExp)), 2)
If (Sgn(nExp) < 0) Then
FormatTemp =
FormatNumber(nValue, 2, vbTrue, vbFalse, vbFalse) & "E" & nExp
Else
FormatTemp =
FormatNumber(nValue, 2, vbTrue, vbFalse, vbFalse) & "E+" & nExp
End If
Case "True/False"
If (CBool(varValue)) Then
FormatTemp = "True"
Else
FormatTemp = "False"
End If
Case "Yes/No"
If (CBool(varValue)) Then
FormatTemp = "Yes"
Else
FormatTemp = "No"
End If
Case "On/Off"
If (CBool(varValue)) Then
FormatTemp = "On"
Else
FormatTemp = "Off"
End If
Case Else ' This is a custom format
If nType = 6 Then ' This is a currency
FormatTemp = FormatCurrencyPerLocale(varValue,
iNumDecimals, LCID)
End If
End Select
End If
If IsEmpty(FormatTemp) Then
FormatTemp = varValue
End If
If FHasNoContent(FormatTemp) Then
Format = " "
Else
Format = FormatTemp
End If
End Function
Function FormatCurrencyPerLocale(varValue,
iNumDecimals, LCID)
Dim CurrentLCID
If LCID >< "" Then CurrentLCID = SetLocale(LCID)
If IsNumeric(iNumDecimals) Then
FormatCurrencyPerLocale = FormatCurrency(varValue,
iNumDecimals)
Else
FormatCurrencyPerLocale = FormatCurrency(varValue)
End If
If Not IsEmpty(CurrentLCID) Then SetLocale CurrentLCID
End Function
Function FHasNoContent(objValue)
FHasNoContent = True
If IsNull(objValue) Then Exit Function
If IsEmpty(objValue) Then Exit Function
If Not IsObject(objValue) Then
If objValue = "" Then Exit Function
Else
If objValue Is Nothing Then Exit Function
End if
FHasNoContent = False
End Function
Function IIf(fCond, varTrue, varFalse)
If fCond Then
IIf = varTrue
Else
IIf = varFalse
End If
End Function
Function Nz(varValue, varReplace)
If FHasNoContent(varValue) Then
Nz = varReplace
Else
Nz = varValue
End If
End Function
Function Sum(strExpr)
Dim nSum, i
nSum = 0
Set objCurrNodeT = objCurrNode
For i = 0 To cGroupCount - 1
Set objCurrNode = objGroupNodes.item(i)
nSum = nSum + ToNumber(Eval(strExpr))
Next
Set objCurrNode = objCurrNodeT
Sum = nSum
End Function
Function Count(strExpr)
Dim nCount, i
If strExpr = "*" Then
Count = cGroupCount
Exit Function
End If
Set objCurrNodeT = objCurrNode
nCount = 0
For i = 0 To cGroupCount - 1
Set objCurrNode = objGroupNodes.item(i)
If Not FHasNoContent(Eval(strExpr)) Then
nCount = nCount + 1
End If
Next
Set objCurrNode = objCurrNodeT
Count = nCount
End Function
Function Avg(strExpr)
Dim nSum
Dim nCount
nSum = Sum(strExpr)
nCount = Count(strExpr)
If nCount > 0 Then
Avg = nSum / nCount
Else
Avg = nSum
End If
End Function
Function Min(strExpr)
Dim varMin, i
Dim varTemp
Set objCurrNodeT = objCurrNode
For i = 0 To cGroupCount - 1
Set objCurrNode = objGroupNodes.item(i)
varTemp = Eval(strExpr)
If IsEmpty(varMin) Or (varTemp < varMin) Then
varMin = varTemp
End If
Next
Set objCurrNode = objCurrNodeT
Min = varMin
End Function
Function Max(strExpr)
Dim varMax, i
Dim varTemp
varMax = Eval(strExpr)
Set objCurrNodeT = objCurrNode
For i = 0 To cGroupCount - 1
Set objCurrNode = objGroupNodes.item(i)
varTemp = Eval(strExpr)
If IsEmpty(varMax) Or (varTemp > varMax) Then
varMax = varTemp
End If
Next
Set objCurrNode = objCurrNodeT
Max = varMax
End Function
Function GetValue(strRef, nType)
' Set Null as the default return value
GetValue = Null
' Return Null if anything goes wrong
On Error Resume Next
Dim objNode
Set objNode = objCurrNode.selectSingleNode(strRef)
If (objNode Is Nothing) Or IsNull(objNode) Or IsEmpty(objNode)
Or Not IsObject(objNode) Then
Exit Function
End If
Dim CurrentLCID
CurrentLCID = SetLocale(1033)
Select Case nType
Case 2 ' adSmallInt
GetValue = CLng(objNode.text)
Case 3 ' adInteger
GetValue = CLng(objNode.text)
Case 20 ' adBigInt
GetValue = CLng(objNode.text)
Case 17 ' adUnsignedTinyInt
GetValue = CLng(objNode.text)
Case 18 ' adUnsignedSmallInt
GetValue = CLng(objNode.text)
Case 19 ' adUnsignedInt
GetValue = CLng(objNode.text)
Case 21 ' adUnsignedBigInt
GetValue = CLng(objNode.text)
Case 4 ' adSingle
GetValue = CDbl(objNode.text)
Case 5 ' adDouble
GetValue = CDbl(objNode.text)
Case 6 ' adCurrency
GetValue = CCur(objNode.text)
Case 14 ' adDecimal
GetValue = CDbl(objNode.text)
Case 131 ' adNumeric
GetValue = CDbl(objNode.text)
Case 139 ' adVarNumeric
GetValue = CDbl(objNode.text)
Case 11 ' adBoolean
GetValue = CBool(objNode.text)
Case 7 ' adDate
GetValue = BuildDateFromStr(objNode.text, True)
Case 133 ' adDBDate
GetValue = BuildDateFromStr(objNode.text, True)
Case 134 ' adDBTime
GetValue = BuildDateFromStr(objNode.text, True)
Case 135 ' adDBTimeStamp
GetValue = BuildDateFromStr(objNode.text, True)
Case 8 ' adBSTR
GetValue = objNode.text
Case 120 ' adChar
GetValue = objNode.text
Case 200 ' adVarChar
GetValue = objNode.text
Case 201 ' adLongVarChar
GetValue = objNode.text
Case 130 ' adWChar:
GetValue = objNode.text
Case 202 ' adVarWChar
GetValue = objNode.text
Case 203 ' adLongVarWChar
GetValue = objNode.text
Case -7 ' Special value used to get
just the date.
GetValue = BuildDateFromStr(objNode.text, False)
Case Else
GetValue = objNode.text
End Select
SetLocale CurrentLCID
End Function
Dim gStaticDate
Function StaticDate()
If IsEmpty(gStaticDate) Then gStaticDate =
GetValue("/*/@generated", -7)
StaticDate = gStaticDate
End Function
Dim gStaticNow
Function StaticNow()
If IsEmpty(gStaticNow) Then gStaticNow =
GetValue("/*/@generated", 7)
StaticNow = gStaticNow
End Function
Function BuildDateFromStr(strDate, fIncludeTime)
Dim CurrentLCID
CurrentLCID = SetLocale(1033)
' This requires that the Locale be set to en-us (1033).
BuildDateFromStr = CDate(Left(strDate,10))
If (fIncludeTime) Then
BuildDateFromStr = BuildDateFromStr +
CDate(Right(strDate,8))
End If
SetLocale CurrentLCID
End Function
Function ArrayItem(arr, index)
If index > UBound(arr) Then
ArrayItem = ""
Else
ArrayItem = arr(index)
End If
End Function
Function HyperlinkPartFromNodeList(nodelist, nPart)
If nodelist.length = 0 Then
HyperlinkPartFromNodeList = ""
Else
HyperlinkPartFromNodeList =
HyperlinkPartFromString(nodelist.item(0).text, nPart)
End If
End Function
Function HyperlinkPart(strRef, nPart)
HyperlinkPart =
HyperlinkPartFromString(GetValue(strRef, 200), nPart)
End Function
Function HyperlinkPartFromString(strHyperlink, nPart)
Dim arrParts
Dim strHyperlinkPart
Dim strAddress, strSubAddress
arrParts = Split(strHyperlink, "#")
Select Case nPart
Case 0 ' acDisplayedValue
strHyperlinkPart = ArrayItem(arrParts, 0)
If strHyperlinkPart = "" Then
strAddress = ArrayItem(arrParts, 1)
strSubAddress = ArrayItem(arrParts, 2)
If strAddress = "" and strSubAddress = "" Then
strHyperlinkPart = ""
ElseIf strSubAddress = "" Then
strHyperlinkPart = strAddress
ElseIf strAddress = "" Then
strHyperlinkPart = strSubAddress
Else
strHyperlinkPart = strAddress & " - " & strSubAddress
End If
End If
Case 1 ' acDisplayText
strHyperlinkPart = ArrayItem(arrParts, 0)
Case 2 ' acAddress
strHyperlinkPart = ArrayItem(arrParts, 1)
Case 3 ' acSubAddress
strHyperlinkPart = ArrayItem(arrParts, 2)
Case 4 ' acScreenTip
strHyperlinkPart = ArrayItem(arrParts, 3)
Case 5 ' acFullAddress
strAddress = ArrayItem(arrParts, 1)
strSubAddress = ArrayItem(arrParts, 2)
If strAddress = "" and strSubAddress = "" Then
strHyperlinkPart = "#"
ElseIf strSubAddress = "" Then
strHyperlinkPart = strAddress
Else
strHyperlinkPart = strAddress & "#" & strSubAddress
End If
End Select
HyperlinkPartFromString = strHyperlinkPart
End Function
]]></msxsl:script>
</xsl:stylesheet>
Some of the things to note are that the language used is VB Script, the elements are processed by the code which forms part of the style sheet file, and the functions in the code are referenced in the second line after the XML processing line. The code is of course enclosed in the CDATA section. It is generic code, only parts of which are used in this simple example. In general, if one were to write XSL for a given XML file, one could hand code the sheet and the amount of code will be much smaller. For those who are interested in generating XSL code, the functions used in this file shown can be very useful; although it can be generated from MS Access, it is included for the sake of completeness.
Summary
The tutorial looked at the Export utility in MS Access 2003 to see how well the data was exported. In the simple example used, exporting to XML was highly satisfactory and provided the various related 'xml' files with good documentation. The Vb script functions in the CDATA section should be valuable to those who are interested in XSL. The import was tested with Microsoft Office Access 2003 (11.6566.6568) SP2 on Office XP Professional Media Center Edition.