1 2 4 import java.io.File ; 5 import java.io.FileReader ; 6 import java.io.IOException ; 7 import java.io.StringReader ; 8 9 import org.xmlpull.v1.XmlPullParser; 10 import org.xmlpull.v1.XmlPullParserException; 11 import org.xmlpull.v1.XmlPullParserFactory; 12 13 18 public class XmlPullCount 19 { 20 public final static String SAMPLE_XML = 21 "<?xml version=\"1.0\"?>\n"+ 22 "\n"+ 23 "<poem xmlns=\"http://www.megginson.com/ns/exp/poetry\">\n"+ 24 "<title>Roses are Red</title>\n"+ 25 "<l>Roses are red,</l>\n"+ 26 "<l>Violets are blue;</l>\n"+ 27 "<l>Sugar is sweet,</l>\n"+ 28 "<l>And I love you.</l>\n"+ 29 "</poem>"; 30 int countChars; 31 int countAttribs; 32 int countSTags; 33 34 public static void main (String args[]) 35 throws XmlPullParserException, IOException 36 { 37 38 39 XmlPullParserFactory factory = XmlPullParserFactory.newInstance( 40 System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); 41 factory.setNamespaceAware(true); 42 System.out.println("using factory "+factory.getClass()); 43 44 XmlPullParser xpp = factory.newPullParser(); 45 System.out.println("using parser "+xpp.getClass()); 46 47 XmlPullCount app = new XmlPullCount(); 48 49 for(int c = 0; c < 2; ++c) { 50 System.out.println("run#"+c); 51 app.resetCounters(); 52 if(args.length == 0) { 53 System.out.println("Parsing simple sample XML length="+SAMPLE_XML.length()); 54 xpp.setInput( new StringReader ( SAMPLE_XML ) ); 55 app.countXml(xpp); 56 } else { 57 59 File f = new File (args[0]); 60 System.out.println("Parsing file: "+args[0]+" length="+f.length()); 61 xpp.setInput ( new FileReader ( args [0] ) ); 62 app.countXml(xpp); 63 } 65 app.printReport(); 66 } 67 System.out.println("finished"); 68 } 69 70 public void resetCounters() { 71 countChars = countSTags = countAttribs = 0; 72 } 73 74 public void printReport() { 75 System.out.println("characters="+countChars 76 +" elements="+countSTags 77 +" attributes="+countAttribs); 78 79 } 80 81 public void countXml(XmlPullParser xpp) throws XmlPullParserException, IOException { 82 83 int holderForStartAndLength[] = new int[2]; 84 85 86 int eventType = xpp.getEventType(); 87 if(eventType == xpp.START_DOCUMENT) { 88 eventType = xpp.next(); 89 } 90 while (eventType != xpp.END_DOCUMENT) { 91 if(eventType == xpp.START_TAG) { 93 ++countSTags; 94 countAttribs += xpp.getAttributeCount(); 95 } else if(eventType == xpp.TEXT) { 96 xpp.getTextCharacters(holderForStartAndLength); 98 int length = holderForStartAndLength[1]; 100 countChars += length; 101 } 102 eventType = xpp.next(); 103 } 104 } 105 } 106 | Popular Tags |