A Program to convert tab delimited data to XML
import java.io.*;
public class BaseballTabToXML {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream(args[0]);
BufferedReader in
= new BufferedReader(new InputStreamReader(fin));
FileOutputStream fout
= new FileOutputStream("baseballstats.xml");
OutputStreamWriter out = new OutputStreamWriter(fout, "UTF-8");
out.write("<?xml version=\"1.0\"?>\r\n");
out.write("<players>\r\n");
String playerStats;
while ((playerStats = in.readLine()) != null) {
String[] stats = splitLine(playerStats);
out.write(" <player>\r\n");
out.write(" <first_name>" + stats[1] + "</first_name>\r\n");
out.write(" <surname>" + stats[0] + "</surname>\r\n");
out.write(" <games_played>" + stats[4] + "</games_played>\r\n");
out.write(" <at_bats>" + stats[6] + "</at_bats>\r\n");
out.write(" <runs>" + stats[7] + "</runs>\r\n");
out.write(" <hits>" + stats[8] + "</hits>\r\n");
out.write(" <doubles>" + stats[9] + "</doubles>\r\n");
out.write(" <triples>" + stats[10] + "</triples>\r\n");
out.write(" <home_runs>" + stats[11] + "</home_runs>\r\n");
out.write(" <stolen_bases>" + stats[12] + "</stolen_bases>\r\n");
out.write(" <caught_stealing>" + stats[14] + "</caught_stealing>\r\n");
out.write(" <sacrifice_hits>" + stats[15] + "</sacrifice_hits>\r\n");
out.write(" <sacrifice_flies>" + stats[16] + "</sacrifice_flies>\r\n");
out.write(" <errors>" + stats[17] + "</errors>\r\n");
out.write(" <passed_by_ball>" + stats[18] + "</passed_by_ball>\r\n");
out.write(" <walks>" + stats[19] + "</walks>\r\n");
out.write(" <strike_outs>" + stats[20] + "</strike_outs>\r\n");
out.write(" <hit_by_pitch>" + stats[21] + "</hit_by_pitch>\r\n");
out.write(" </player>\r\n");
}
out.write("</players>\r\n");
out.close();
in.close();
}
catch (IOException e) {
System.err.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: java BaseballTabToXML input_file.tab");
}
}
public static String[] splitLine(String playerStats) {
// count the number of tabs
int numTabs = 0;
for (int i = 0; i < playerStats.length(); i++) {
if (playerStats.charAt(i) == '\t') numTabs++;
}
int numFields = numTabs + 1;
String[] fields = new String[numFields];
int position = 0;
for (int i = 0; i < numFields; i++) {
StringBuffer field = new StringBuffer();
while (position < playerStats.length()
&& playerStats.charAt(position++) != '\t') {
field.append(playerStats.charAt(position-1));
}
fields[i] = field.toString();
}
return fields;
}
}