Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using <code>ReadAndPrintXMLFileWithStAX</code> below, when I compare with <code>ReadAndPrintXMLFileWithSAX</code> from the <a href="https://stackoverflow.com/a/12271247/383861">answer given by gontard</a> the StAX approach is faster. My test involved running both sample code <code>500000</code> times on JDK 1.7.0_07 for the Mac.</p> <pre><code>ReadAndPrintXMLFileWithStAX: 103 seconds ReadAndPrintXMLFileWithSAX: 125 seconds </code></pre> <hr> <p><strong>ReadAndPrintXMLFileWithStAX (using Java SE 7)</strong></p> <p>Below is a more optimized StAX (JSR-173) example using <code>XMLStreamReader</code> instead of <code>XMLEventReader</code>.</p> <pre><code>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"); } } </code></pre> <p><strong>Output</strong></p> <pre><code>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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload