LightBlog

Tuesday, March 4, 2008

Convert XML to CSV, with XSL


This VBScript will use the MSXML DLL from Microsoft to transform an XML file with XSL to a semi colon separated file, which can be easily imported in a host of other applications that are not completely XML aware yet.

For this sample, I used an XML file from the Internet, and downloaded the PlantCatolog.xml from the the W3schools site. And as a starting point for the XSL file, With these two files, we only have to write the VBScript to transform the XML to our resulting file.
First, we save the XML file on the C disk as testme.xml and the XSL file as testme.xsl. Note that the difference is in the extension, so we can use the same filename to keep things simple. Our resulting file will also be on C and will be called testme.txt.
Now, fire up Notepad and add this code, creating the needed variables first:

Dim xmlSource

Dim xmlXForm

Dim strErr

Dim strResult

Dim fso, file

Dim strPath

Const ForWriting = 2

Set xmlSource = CreateObject("MSXML.DOMDocument")

Set xmlXForm = CreateObject("MSXML.DOMDocument")

xmlSource.validateOnParse = True

xmlXForm.validateOnParse = True

xmlSource.async = False

xmlXForm.async = False

' This loads the text that I want to transform
xmlSource.Load "c:\testme.xml"
If Err.Number <> 0 Then
strErr = Err.Description & vbCrLf
strErr = strErr & xmlSource.parseError.reason & " line: " & _
xmlSource.parseError.Line & " col: " & _
xmlSource.parseError.linepos & _
" text: " & xmlSource.parseError.srcText
MsgBox strErr, vbCritical, "Error loading the XML"
End If
' This loads the XSLT transform
xmlXForm.Load "c:\testme.xsl"
If Err.Number <> 0 Then
strErr = Err.Description & vbCrLf
strErr = strErr & xmlSource.parseError.reason & " line: " & _
xmlSource.parseError.Line & " col: " & _
xmlSource.parseError.linepos & _
" text: " & xmlSource.parseError.srcText
MsgBox strErr, vbCritical, "Error loading the Transform"
End If

' This transforms the data in xmlSource
strResult = xmlSource.transformNode(xmlXForm)
If Err.Number <> 0 Then
strErr = Err.Description & vbCrLf
strErr = strErr & xmlSource.parseError.reason & _
" line: " & xmlSource.parseError.Line & _
" col: " & xmlSource.parseError.linepos & _
" text: " & xmlSource.parseError.srcText
MsgBox strErr, vbCritical, "Error executing the Transform"
End If

Set fso = CreateObject("Scripting.FileSystemObject")
strPath = "c:\testme.txt"
' open the file
Set file = fso.opentextfile(strPath, ForWriting, True)
' write the info to the file
file.write strResult
' close and clean up
file.Close

For this last step, we used the FileSystemObject which makes writing files in cases like this very easy. The download adds some cleanup for the objects, and I’ll leave that out here.





No comments:

BlogCatalog

Adbox