Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

308 HOUR 21: Reading and Writing XML Data


5: public String[] title= new String[15];
6: public String[] link= new String[15];
7: public intcount= 0;
8:
9: publicAggregator(String rssUrl) {
10: try {
11: // retrieve the XML document
12: Builder builder = new Builder();
13: Document doc = builder.build(rssUrl);
14: // retrieve the document’s root element
15: Element root = doc.getRootElement();
16: // retrieve the root’s channel element
17: Element channel = root.getFirstChildElement(“channel”);
18: // retrieve the item elements in the channel
19: if (channel != null) {
20: Elements items = channel.getChildElements(“item”);
21: for (int current = 0; current < items.size(); current++) {
22: if (count > 15) {
23: break;
24: }
25: // retrieve the current item
26: Element item = items.get(current);
27: Element titleElement = item.getFirstChildElement(“title”);
28: Element linkElement = item.getFirstChildElement(“link”);
29: title[current] = titleElement.getValue();
30: link[current] = linkElement.getValue();
31: count++;
32: }
33: }
34: } catch(ParsingException exception) {
35: System.out.println(“XML error: “+ exception.getMessage());
36: exception.printStackTrace();
37: } catch(IOException ioException) {
38: System.out.println(“IO error: “+ ioException.getMessage());
39: ioException.printStackTrace();
40: }
41: }
42:
43: public voidlistItems() {
44: for (int i = 0; i < 15; i++) {
45: if (title[i] != null) {
46: System.out.println(“\n” + title[i]);
47: System.out.println(link[i]);
48: i++;
49: }
50: }
51: }
52:
53: public static voidmain(String[] arguments) {
54: if (arguments.length> 0) {

LISTING 21.4 Continued
Free download pdf