Using Flash with Zinc v2.5 to Convert and Save a CSV file to an XML file - Page 3

Converting the CSV Data into XML Data

The function convertToXml will do the CSV to XML conversion. In this function, first the user is asked where they would like to save their XML file using the Browse Dialog we used in the openCSV function. The first 8 lines of this function do this:

Here, the Browse Dialogs is customised in the same way we customised it before. The 4th line uses a, 'if' statement to determine whether the projector is being run on Windows or the Mac and displays the relevant Browse Dialog (The Mac version of Zinc has a dedicated SaveAs Dialog that we can use, mdm.Dialogs.BrowseFileToSave.show).

The following code will convert the CSV data into XML Data and save that to a file specified by the user :

First of all we need to create an XML object
Then we create our 'root' node (myDatabase) which will contain the whole database
An array 'theDB' is created which holds the database (each array value will hold a record)
A 'for' loop is started which will loop through each array value (record in our database)
'Record' nodes are created which will hold all the data for each record

Although CSV files normally use commas as field delimiters, some database managing programs may allow you to export CSV data and use either comma, semicolon, tabs and other characters as delimeters. In our example, code to handle commas, semicolons and tabs as delimeters has been included in these 5 lines (delim.value.toString() refers to the combobox in the example fla which allows the user to select which delimeter our program should look out for).

Our TextNode is inserted into our 'Element'
Our 'Element' is inserted into our 'Record'
When every field has been added to its respective record we then add that record to our 'root' node
When every record has been added to the root node we add all that data to our XML object

var XMLdata = myXML.toString();

As XML is simply text data, we need to convert our XML object to String data by using 'myXML.toString()' so that it can be saved correctly as an XML file.