1 9 10 package org.dom4j.samples; 11 12 import org.dom4j.Attribute; 13 import org.dom4j.Comment; 14 import org.dom4j.Document; 15 import org.dom4j.Element; 16 import org.dom4j.ProcessingInstruction; 17 import org.dom4j.Text; 18 import org.dom4j.Visitor; 19 import org.dom4j.VisitorSupport; 20 21 27 public class CountDemo extends SAXDemo { 28 29 private int numCharacters; 30 31 private int numComments; 32 33 private int numElements; 34 35 private int numAttributes; 36 37 private int numProcessingInstructions; 38 39 public static void main(String [] args) { 40 run(new CountDemo(), args); 41 } 42 43 public CountDemo() { 44 } 45 46 protected void process(Document document) throws Exception { 47 numCharacters = 0; 48 numComments = 0; 49 numElements = 0; 50 numAttributes = 0; 51 numProcessingInstructions = 0; 52 53 Visitor visitor = new VisitorSupport() { 54 55 public void visit(Element node) { 56 ++numElements; 57 } 58 59 public void visit(Attribute node) { 60 ++numAttributes; 61 } 62 63 public void visit(Comment node) { 64 ++numComments; 65 } 66 67 public void visit(ProcessingInstruction node) { 68 ++numProcessingInstructions; 69 } 70 71 public void visit(Text node) { 72 String text = node.getText(); 73 if (text != null) { 74 numCharacters += text.length(); 75 } 76 } 77 }; 78 79 println("Document: " + document.getName() + " has the following"); 80 println("Elements\tAttributes\tComments\tPIs\tCharacters"); 81 82 document.accept(visitor); 83 84 println(numElements + "\t\t" + numAttributes + "\t\t" + numComments 85 + "\t\t" + numProcessingInstructions + "\t" + numCharacters); 86 } 87 } 88 89 127 | Popular Tags |