I have this below XML file
Kiran
Pai
22
Using ReadAndPrintXMLFileWithStAX below, when I compare with ReadAndPrintXMLFileWithSAX from the answer given by gontard the StAX approach is faster. My test involved running both sample code 500000 times on JDK 1.7.0_07 for the Mac.
ReadAndPrintXMLFileWithStAX: 103 seconds
ReadAndPrintXMLFileWithSAX: 125 seconds
ReadAndPrintXMLFileWithStAX (using Java SE 7)
Below is a more optimized StAX (JSR-173) example using XMLStreamReader instead of XMLEventReader.
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.stream.*;
public class ReadAndPrintXMLFileWithStAX {
public static void main(String argv[]) throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream("book.xml");
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(in);
streamReader.nextTag(); // Advance to "book" element
streamReader.nextTag(); // Advance to "person" element
int persons = 0;
while (streamReader.hasNext()) {
if (streamReader.isStartElement()) {
switch (streamReader.getLocalName()) {
case "first": {
System.out.print("First Name : ");
System.out.println(streamReader.getElementText());
break;
}
case "last": {
System.out.print("Last Name : ");
System.out.println(streamReader.getElementText());
break;
}
case "age": {
System.out.print("Age : ");
System.out.println(streamReader.getElementText());
break;
}
case "person" : {
persons ++;
}
}
}
streamReader.next();
}
System.out.print(persons);
System.out.println(" persons");
}
}
Output
First Name : Kiran
Last Name : Pai
Age : 22
First Name : Bill
Last Name : Gates
Age : 46
First Name : Steve
Last Name : Jobs
Age : 40
3 persons