JAXP Usage

Here is a simple quick start for getting up and running with JSpiff and JAXB quickly. An JUnit Test Example is also included in the distribution to show you how easy it is to use JSpiff with JAXB.

Creating new XSPF Playlist

Create a new PlaylistType object and add tracks to it.

// all JAXB objects are created using ObjectFactory
final ObjectFactory factory = new ObjectFactory();

// create the new blank playlist
final PlaylistType playlist = factory.createPlaylistType();
playlist.setTitle("Melloware XSPF Playlist");
playlist.setCreator("Melloware User");
playlist.setInfo("http://melloware.com/");
playlist.setVersion("1");
playlist.setImage("http://melloware.com/images/header.jpg");
playlist.setIdentifier(Integer.toString(super.hashCode()));
playlist.setLicense("http://www.apache.org/licenses/LICENSE-2.0.txt");

// make a JAXB element out of the final Playlist
final JAXBElement element = factory.createPlaylist(playlist);
           

Loading an XSPF playlist from file

Unmarshall the document using the Unmarshaller object.

// create the file
final File file = new File("playlist.xml);

// need to tell JAXB where the XSPF jaxb classes are located
final JAXBContext jc = JAXBContext.newInstance("com.melloware.jspiff.jaxb");

// unmarshal the XML document into the playlist class hierarchy
final Unmarshaller u = jc.createUnmarshaller();
final JAXBElement element = (JAXBElement)u.unmarshal(file);
final PlaylistType playlist = (PlaylistType)element.getValue();

// get the playlist title
System.out.println(playlist.getTitle());

// loop through the tracks printing out each track title
for (Iterator iter = playlist.getTrackList().getTrack().iterator(); iter.hasNext();) {
   TrackType track = (TrackType)iter.next();
   System.out.println(track.getTitle());
}
           

Saving an XSPF playlist to file

Marhsall the document back together and send to an output stream.

final PlaylistType playlist = factory.createPlaylistType();
... add stuff to the playlist

// get the outermost JAXB Element 
final JAXBElement element = factory.createPlaylist(playlist);

// make an xml document out of it
final Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(element, new FileOutputStream("playlist-out.xml"));