I am trying to create a Java program that finds the element (I am new to XML and don't understand the jargon. Is it even called an element?!?) whose value is highest and returns the element which surrounds it. Here is an example of the code:
<conversation input="HELLO">
<output hits="3">
HI MATE
</output>
<output hits="8">
HELLO
</output>
</conversation>
It would find which "output" has the most "hits" and return the value it contains (EX. HELLO). i am trying to use stAX but it you know of a better way to do this using something different, go right ahead!
EDIT Here is the requested full code:
package charles;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.swing.JOptionPane;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
public class NewClass {
//Memory
static String currentResult = null;
static int highestHits = 0;
private static String filename = "\\Files\\Java\\Projects\\CHARLES\\src\\charles\\Memory.xml";
static XMLEventReader reader;
public static void main(String args[]) throws XMLStreamException, FileNotFoundException {
try {
filename = "\\Files\\Java\\Projects\\CHARLES\\src\\charles\\Memory.xml";
} catch (ArrayIndexOutOfBoundsException aioobe) {
System.exit(0);
}
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader =
factory.createXMLEventReader(new FileReader(filename));
while (reader.hasNext()) {
XMLEvent e = reader.nextEvent();
System.out.println("ID:" + e.hashCode() + "[" + e + "]");
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private static void analyze() {
while (reader.hasNext()) {
int event = (int) reader.next();
if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals(input)) {
int currentHits = Integer.parseInt(reader.getAttributeValue(0));
if (currentHits > highestHits) {
highestHits = currentHits;
reader.next();
currentResult = reader.getText();
}
}
}
}
}