Sunday, 4 December 2011

Parsing iTunes Music Library xml using SAX Parser

If you want to parse your itunes library file and use it for music applications, heres a bit of code to help you do that.

public class ItunesParser extends DefaultHandler{
Map tracksMap = null;
private String current_tag;
private String prev_val;
private StringBuilder tempVal = new StringBuilder();
private MUDTrackBean tempTrack;
private String trackid;
private boolean isParentArray=false;
private String fileLoc;

public Map itunesParser(String fileLoc) throws SAXException {

tracksMap = new HashMap();
this.fileLoc = fileLoc;
parseDocument();

//printData();
return tracksMap;
}
private void parseDocument() throws SAXException {

try{
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
spf.setFeature("http://apache.org/xml/features/validation/schema", true);

SAXParser sp = spf.newSAXParser();
sp.parse(fileLoc, this);
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
current_tag = qName.trim();
prev_val = tempVal.toString();
tempVal = new StringBuilder();

if(qName.equalsIgnoreCase("array")) {
isParentArray = true;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(current_tag.equalsIgnoreCase("string")) {
tempVal.append(new String(ch, start, length));
} else {
tempVal = new StringBuilder(new String(ch, start, length));
}

}
public void endElement(String uri, String localName, String qName) throws SAXException {
String tempValStr=tempVal.toString();
if(qName.equalsIgnoreCase("dict") && !isParentArray)
{
if(tempTrack!=null)
{
if(tempTrack.getTrackid()!=null)
{
tracksMap.put(trackid, tempTrack);
}
}
}

else if (qName.equalsIgnoreCase("key") && !isParentArray)
{

if(tempValStr.equalsIgnoreCase("Track ID"))
tempTrack = new MUDTrackBean();
}
else if(qName.equals("integer") && prev_val.equalsIgnoreCase("Track ID") && !isParentArray)
{
trackid = tempValStr;
tempTrack.setTrackid(trackid);
}
else if(qName.equals("string") && prev_val.equalsIgnoreCase("Name") && !isParentArray)
{
tempTrack.setTrackTitle(tempValStr);
}
else if (qName.equalsIgnoreCase("string") && prev_val.equalsIgnoreCase("Artist") && !isParentArray)
{
tempTrack.setArtist(tempValStr);
}
else if (qName.equalsIgnoreCase("string") && prev_val.equalsIgnoreCase("Album") && !isParentArray)
{
tempTrack.setAlbum(tempValStr);
}
else if (qName.equalsIgnoreCase("integer") && prev_val.equalsIgnoreCase("Play Count") && !isParentArray)
{
tempTrack.setPlayCount(Integer.parseInt(tempValStr));
}
}

}