Google Apps Script to dynamically convert csv file to xml file.

CodeGuy
March 21, 2016

Here, you will learn how to convert a csv file to xml file using Class Utilities Service. This service provides utilities for string encoding/decoding, date formatting, JSON manipulation, and other miscellaneous tasks. Then, using XML Service for parsing, navigating, and programmatically creating a XML output.

Sometimes, sites serve the content via CSV (Comma Separated Values), Since, for a CSV official standard format does not exist, though RFC 4180 provides a de facto standard for many aspects of it. Structuring to XML would prove  great results for most of the web and other applications.

Here is a app script source code, copy it to app script editor and run.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function doGet(e) {

    //xml header
    var xml1 = '<?xml version="1.0" encoding="utf-8"?><Items></Items>';

    //get a csv file 
    var getFile = UrlFetchApp.fetch('https://drive.google.com/uc?export=download&id=0BwhjVbB5GFrMdHNrekVfcUVfaTA').getContentText();
    var data = Utilities.parseCsv(getFile);

    var document = XmlService.parse(xml1);
    var root = document.getRootElement();

    for (var j = 1; j < data.length; j++) {
        //create a binding element named Item
        var row = XmlService.createElement('Item');
        var vbl = XmlService.createElement('Detail1').setText(data[j][0]);
        row.addContent(vbl);
        var vb2 = XmlService.createElement('Detail2').setText(data[j][1]);
        row.addContent(vb2);
        var vb3 = XmlService.createElement('Detail3').setText(data[j][2]);
        row.addContent(vb3);
        var vb4 = XmlService.createElement('Detail4').setText(data[j][3]);
        row.addContent(vb4);
        var vb5 = XmlService.createElement('Detail5').setText(data[j][4]);
        row.addContent(vb5);
        var vb6 = XmlService.createElement('Detail6').setText(data[j][5]);
        row.addContent(vb6);

        root.addContent(row);
    }
    return ContentService.createTextOutput('<?xml version="1.0" encoding="utf-8"?>' + XmlService.getPrettyFormat().format(root)).setMimeType(ContentService.MimeType.XML);
}

0 comments

Do not spam.

Like us on Facebook

Blog Archive