A Shortcut
import java.io.*;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
public class BaseballTabToXMLShortcut {
public static void main(String[] args) {
Element root = new Element("players");
try {
FileInputStream fin = new FileInputStream(args[0]);
BufferedReader in
= new BufferedReader(new InputStreamReader(fin));
String playerStats;
while ((playerStats = in.readLine()) != null) {
String[] stats = splitLine(playerStats);
Element player = new Element("player");
player.addChild((new Element("first_name")).setContent(stats[1]));
player.addChild((new Element("surname")).setContent(stats[0]));
player.addChild((new Element("games_played")).setContent(stats[4]));
player.addChild((new Element("at_bats")).setContent(stats[6]));
player.addChild((new Element("runs")).setContent(stats[7]));
player.addChild((new Element("hits")).setContent(stats[8]));
player.addChild((new Element("doubles")).setContent(stats[9]));
player.addChild((new Element("triples")).setContent(stats[10]));
player.addChild((new Element("home_runs")).setContent(stats[11]));
player.addChild((new Element("runs_batted_in")).setContent(stats[12]));
player.addChild((new Element("stolen_bases")).setContent(stats[13]));
player.addChild((new Element("caught_stealing")).setContent(stats[14]));
player.addChild((new Element("sacrifice_hits")).setContent(stats[15]));
player.addChild((new Element("sacrifice_flies")).setContent(stats[16]));
player.addChild((new Element("errors")).setContent(stats[17]));
player.addChild((new Element("passed_by_ball")).setContent(stats[18]));
player.addChild((new Element("walks")).setContent(stats[19]));
player.addChild((new Element("strike_outs")).setContent(stats[20]));
player.addChild((new Element("hit_by_pitch")).setContent(stats[21]));
root.addChild(player);
}
Document doc = new Document(root);
// serialize it into a file
FileOutputStream fout
= new FileOutputStream("baseballstats.xml");
XMLOutputter serializer = new XMLOutputter();
serializer.output(doc, fout);
fout.flush();
fout.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;
}
}