We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I have the following XML code:
<?xml version="1.0"?>
<data type="artists">
<artist name="Astroid Power Up">
<album>Google Plex</album>
</artist>
<artist name="Battles">
<album>Gloss Drop</album>
<album>La Di Da Di</album>
</artist>
<artist name="Brad Mehldau">
<album>Day is Done</album>
<album>House on Hill</album>
<album>Largo</album>
<album>Modern Music</album>
</artist>
<artist name="Bugge Wesseltoft">
<album>Trialogue</album>
</artist>
<artist name="David Sylvian">
<album>Gone to Earth</album>
</artist>
</data>
and I want to create an Array of the kind: artist[artistName][albumsByArtist]. For example, artist[0][0] = "Battles" artist[0][1] = "Gloss Drop" artist[0][2] = "La Di Da Di" (another more optimal structure suggestion would be welcome)
I made an Array containing the artist name, and for each artist, an Array with each oh his/her albums. I can't find a way to associate the artist with the albums though.
XML data;
String[] artists;
void setup() {
data = loadXML("data.xml");
artists = new String[0];
for (XML artist : data.getChildren("artist")) {
String n = artist.getString("name");
artists = append(artists, n); // set name to first element of array
String[] albumsByArtist = new String[0];
for (XML album : artist.getChildren("album")) {
String a = album.getContent();
albumsByArtist = append(albumsByArtist, a); // fill albumsByArtist with albums names
}
}
}
Answers
Tricky
Line 2 should be 2D as in
[][]
Line 12 should be obsolete
But there are a few details there.... tricky
It's always hard when you use append
Instead declare the thing in line 6 with the correct length of the array
apart from a 2D array I could imagine a class artist that holds the artist name plus other data about him or her plus an ArrayList for the Albums (of class Album with other data on it)
also, look ar hashMap which allows you to look up artists/Strings more easily
here is the 2D array:
Thanks!
I created an Artist class after all, it was simpler and perhaps more efficient. In your example, I am not sure I understand this line you used to fill the album names in the second dimension:
artists[i] = (String[]) append(artists[i], a);
yeah, read the reference on append
we need to help (cast) append to know what type it is giving out as a result, therefore we need to say
(String[])
also, since it is a 2D array, artists[i] is referring to one array, namely the 2nd dimension of the array
please note that the arrays artists[0] and artists[1] and artists[2].... are of different length, depending on the number of albums
So it is not a rectangular grid but more lines (arrays) of different length in the main (first) array
In java a 2D array is an array of arrays basically