1 21 22 package nu.xom.samples; 23 24 import java.io.IOException ; 25 26 import nu.xom.Builder; 27 import nu.xom.Document; 28 import nu.xom.Element; 29 import nu.xom.Elements; 30 import nu.xom.ParsingException; 31 32 33 45 public class ExampleLister { 46 47 private static int chapter = 0; 48 49 public static void list(Element root) { 50 51 chapter = 0; 52 if (root.getLocalName().equals("chapter")) { 53 chapter++; 54 exampleNumber = 0; 55 list(root); 56 } 57 else { 58 Elements elements = root.getChildElements(); 59 for (int i = 0; i < elements.size(); i++) { 60 Element child = elements.get(i); 61 if (child.getLocalName().equals("chapter")) { 62 chapter++; 63 exampleNumber = 0; 64 findExamples(child); 65 } 66 else { 67 list(child); 68 } 69 } 70 71 } 72 73 } 74 75 76 private static int exampleNumber = 0; 77 78 private static void findExamples(Element element) { 79 80 Elements elements = element.getChildElements(); 81 for (int i = 0; i < elements.size(); i++) { 82 Element child = elements.get(i); 83 if (child.getQualifiedName().equals("example")) { 84 printExample(child); 85 } 86 else { 87 findExamples(child); 88 } 89 } 90 91 } 92 93 94 private static void printExample(Element example) { 95 96 exampleNumber++; 97 Element title = example.getFirstChildElement("title"); 98 99 String caption = "Example " + chapter + "." + exampleNumber 100 + ": " + title.getValue(); 101 102 System.out.println(caption); 103 104 } 105 106 107 public static void main(String [] args) { 108 109 if (args.length <= 0) { 110 System.out.println("Usage: java nu.xom.samples.ExampleLister URL"); 111 return; 112 } 113 String url = args[0]; 114 115 try { 116 Builder builder = new Builder(); 117 Document document = builder.build(args[0]); 119 120 list(document.getRootElement()); 122 123 } 124 catch (ParsingException ex) { 125 System.out.println(ex); 126 } 127 catch (IOException ex) { 128 System.out.println( 129 "Due to an IOException, the parser could not read " + url 130 ); 131 System.out.println(ex); 132 } 133 134 } 136 } | Popular Tags |