You could just use the java XML DOM classes to do this straightforwardly by passing over all the 'output' elements and recording which has the greatest 'hits' attribute. Say you have converted the XML to a DOM Document object 'doc', then you pass it to a method like this (returns null if there are no 'output' elements or if there are no non-zero hit attributes):
public String getHighest(Document doc) {
NodeList list = doc.getElementsByTagName("output");
String currentResult = null;
int highestHit = 0;
for (int i = 0; i < list.getLength(); i++) {
int hits = Integer.parseInt(((Element) list.item(i)).getAttribute("hits"));
if (hits > highestHit) {
highestHit = hits;
currentResult = list.item(i).getTextContent();
}
}
return currentResult;
}
This would only be appropriate if the XML document is not very large, as the DOM parser will load the whole of the XML tree into memory before it can be traversed. The parsed XML tree will typically take up 5 to 10 times more space than the XML in a file. So, if your XML file is larger than a few MB, you should use a SAX or StAX parser instead.
For StAX parsing this type of information, say you have an XMLStreamReader called 'reader', then the following snippet would work (though you should probably include some error-handling capability):
int highestHits = 0;
String currentResult = null;
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("output")) {
int currentHits = Integer.parseInt(reader.getAttributeValue(0));
if (currentHits > highestHits) {
highestHits = currentHits;
reader.next();
currentResult = reader.getText();
}
}
}
Edit re: updated code:
I think the problem is that in your code 'reader' is an XMLEventReader (well, the reason why it would not compile). But in 'analyze' you call methods on it that are from XMLStreamReader. Just make sure you use an XMLStreamReader to carry out the operations in the method 'analyze'.