我正在尝试创建一个 Java 程序来查找元素(我是 XML 新手,不懂行话。它甚至被称为元素吗?!?),其值最高并返回围绕它的元素。以下是代码示例:
<conversation input="HELLO">
<output hits="3">
HI MATE
</output>
<output hits="8">
HELLO
</output>
</conversation>
它将找出哪个“输出”具有最多的“命中”并返回它包含的值(例如 HELLO)。我正在尝试使用 stAX,但如果您知道使用不同的方法来做到这一点的更好方法,那就继续吧!
编辑这是请求的完整代码:
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();
}
}
}
}
}