ZwiftBooks Goes StAX
Now let’s look at how we might implement our XML extraction of ISBNs with StAX. A StAX version might be useful for our ZwiftBooks warehouse manager who has XML documents delivered to his cell phone and needs a lean parser to deliver alerts when ISBNs are encountered. Listing 5 shows the code.
Listing 5 Using StAX to pull ISBN attributes from XML.
1. import java.io.FileReader; 2. import java.util.Iterator; 3. import javax.xml.stream.*; 4. import javax.xml.namespace.QName; 5. import com.bea.xml.stream.util.ElementTypeNames; 6. 7. /** 8. * A simple parsing example that illustrates 9. * the XMLStreamReader class. 10. * 11. */ 12. 13. public class ZBStaxParse { 14. private static String filename = "EuroBooks.xml"; 15. 16. public static void main(String[] args) throws Exception { 17. 18. // Specify the Parser Factory we want to use 19. System.setProperty("javax.xml.stream.XMLInputFactory", 20. "com.bea.xml.stream.MXParserFactory"); 21. 22. // Get an input factory 23. XMLInputFactory xmlif = XMLInputFactory.newInstance(); 24. 25. // Instantiate a reader 26. XMLStreamReader xmlr = 27. xmlif.createXMLStreamReader(new FileReader(filename)); 28. 29. // Parse the XML 30. while(xmlr.hasNext()){ 31. handleEvent(xmlr); 32. xmlr.next(); 33. } 34. 35. } 36. 37. private static void handleEvent(XMLStreamReader xmlr) { 38. 39. switch (xmlr.getEventType()) { 40. 41. case XMLStreamConstants.START_DOCUMENT: 42. System.out.print("Beginning StAX Parse"); 43. break; 44. 45. case XMLStreamConstants.START_ELEMENT: 46. 47. if(xmlr.hasName()){ 48. String localName = xmlr.getLocalName(); 49. if (localName.equals("book")) { 50. System.out.print(localName); 51. processAttributes(xmlr); 52. } 53. } 54. break; 55. 56. case XMLStreamConstants.END_ELEMENT: 57. System.out.print("StAX Parsing Complete"); 58. break; 59. } 60. 61. } 62. 63. } 64. 65. 66. private static void processAttributes(XMLStreamReader xmlr){ 67. 68. for (int i=0; i < xmlr.getAttributeCount(); i++) { 69. processAttribute(xmlr,i); 70. } 71. } 72. 73. private static void processAttribute(XMLStreamReader xmlr, int index) { 74. String localName = xmlr.getAttributeLocalName(index); 75. if (localName.equals("isbn")) { 76. String value = xmlr.getAttributeValue(index); 77. System.out.println("Alert: " + localName + " = " + value); 78. } 79. } 80. }
The critical lines in Listing 5 are lines 30–32, in which the StAX pull loop is defined. Here the application controls when it needs to get information from the parser. This is especially important for a cell phone, since resources are limited and we don’t want a parser thread continuously calling the handler, possibly slowing down more important phone operations.