Archive

Posts Tagged ‘File I/O’

DATA pt. 3 – File I/O with jQuery and Titanium

August 25th, 2009 Ali Faiz No comments

This is part of the continuing series of articles on Developing Appcelerator Titanium Applications (DATA)

Opening an XML file dialog in Titanium

The props variable specifies that only xml files will be highlighted and accepted in the file dialog. In order to highlight and accept all file types, just make props and empty array: var props = {};

var props = {multiple:false,types:['xml']};
Titanium.UI.openFileChooserDialog(function(filenames) {
	if (filenames[0]){
		Editor.load_file(filenames[0]);
	}
},props);

Reading an XML file

Here are the ways to read an xml (or any) file using both jQuery and Titanium. In both examples, lambda represents a function pointer.

jQuery

	$.get(filename,lambda);

Titanium

	var f = Titanium.Filesystem.getFile(filename);
	var xml = ""+f.read();
	lambda(xml);

Writing an XML file

This of course can only be done with Titanium. Below is how we formatted the xml to pretty print the xml string before writing out to the file. The raw xml string doesn’t lay out nicely so we have to add some spacing.

formatXml: function(xml, lambda) {
    var formatted = '';
    var reg = /(>)(<)(\/*)/g;
    xml = xml.replace(reg, '$1\r\n$2$3');
    var pad = 0;
    jQuery.each(xml.split('\r\n'), function(index, node) {
        var indent = 0;
        if (node.match( /.+<\/\w[^>]*>$/ )) {
            indent = 0;
        } else if (node.match( /^<\/\w/ )) {
            if (pad != 0) {
                pad -= 1;
            }
        } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) {
            indent = 1;
		} else {
            indent = 0;
		}
 
        var padding = '';
        for (var i = 0; i < pad; i++) {
            padding += '  ';
		}
 
        formatted += padding + node + '\r\n';
        pad += indent;
	});
    lambda(formatted);
},

Below is the code that actually writes out to the filesystem. If the file represented by the filename already exists, the write simply overwrites it. If the file doesn’t exist, a new one with that filename is created. Because of the way we had to parse the xml read in, it was necessary to tack on the the xml header.

try {
	var TFS = Titanium.Filesystem;
	var file = TFS.getFile(filename);
	Editor.formatXml(Editor.currentopenfile.filexml, function(xml) {
		header = '<?xml version="1.0" encoding="UTF-8"?>';
		file.write(header+xml);
		var contents = file.read();
	});
} catch (squash) {
	alert("Failed to write to File");
}

Technorati Tags: , , , ,