/* Solution to Chapter 21, Exercise 1 in Teach Yourself Java in 21 Days (Eighth Edition) by Rogers Cadenhead. */ package com.java21days.banko; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.swing.JOptionPane; import nu.xom.Builder; import nu.xom.Document; import nu.xom.Element; import nu.xom.Elements; import nu.xom.ParsingException; import nu.xom.Serializer; import nu.xom.Text; public class ScoreKeeper { private static final String FILENAME = "banko-scores.xml"; public ScoreKeeper() { } public static void update(int newScore) { try { Builder bob = new Builder(); File xmlFile = new File(FILENAME); Document doc = bob.build(xmlFile); Element root = doc.getRootElement(); Elements players = root.getChildElements("Player"); for (int i = 0; i < players.size(); i++) { Element player = players.get(i); Element name = player.getFirstChildElement("Name"); Element score = player.getFirstChildElement("Score"); int oldScore = Integer.parseInt(getValue(score)); if (newScore > oldScore) { String newName = JOptionPane.showInputDialog(null, "New high score! Enter your name:"); if (name.getChildCount() > 0) { name.getChild(0).detach(); } name.appendChild(newName); score.getChild(0).detach(); score.appendChild("" + newScore); FileOutputStream f = new FileOutputStream(FILENAME); Serializer output = new Serializer(f, "ISO-8859-1"); output.setIndent(2); output.write(doc); return; } } } catch (ParsingException | IOException exc) { System.out.println("Error: " + exc.getMessage()); } } private static String getValue(Element element) { if (element != null) { Text elementText = (Text) element.getChild(0); return elementText.getValue(); } return ""; } public static void main(String[] arguments) { ScoreKeeper.update(15); } }