Witam, mam plik xml ktory sam wygenerowalem swoim programem, lecz mam problem z odczytaniem tego pliku w programie do konwersji z xml do javy. Zamieszczam klase Artist, plik xml oraz main.
package przyklad; import java.util.ArrayList; public class Artist { public String name; public boolean isAlive; public String url; public ArrayList<Album> albums = new ArrayList<Album>(); public Artist(String name, boolean isAlive, String url) { this.name = name; this.isAlive = isAlive; this.url = url; } public void addAlbum(Album album) { albums.add(album); } } class Album { public String title; public int noOfrecords; public int year; public Album(String title, int noOfrecords, int year) { this.title = title; this.noOfrecords = noOfrecords; this.year = year; } }
package przyklad; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class przyklad{ public static void main(String[] args) { String filename = "plik.xml"; ArrayList<Artist> artysci = new ArrayList<Artist>(); artysci = xml2ArrayListArtist(filename); System.out.println(artysci); } public static ArrayList<Artist> xml2ArrayListArtist(String filename) { String xml = ""; String strLine = ""; if (filename != null) { try { FileInputStream f = new FileInputStream(filename); DataInputStream in = new DataInputStream(f); BufferedReader r = new BufferedReader(new InputStreamReader(in)); while ((strLine = r.readLine()) != null) xml += strLine; in.close(); XStream mapping = new XStream(new DomDriver()); return (ArrayList<Artist>) mapping.fromXML(xml); } catch (Exception e) { System.out.println(e); System.exit(0); } } return null; } }
<list> - <przyklad2.Artist><name>wiesiek</name><isAlive>false</isAlive> - <albums> - <przyklad2.Album><title>Bix Beiderbecke with the Paul Whiteman Orchestra</title><noOfrecords>5</noOfrecords><year>1928</year></przyklad2.Album> - <przyklad2.Album><title>Bix Beiderbecke and His Gang</title><noOfrecords>6</noOfrecords><year>1927</year></przyklad2.Album></albums></przyklad2.Artist></list>