1 9 10 package org.dom4j.samples; 11 12 import java.io.BufferedReader ; 13 import java.io.InputStreamReader ; 14 import java.util.Iterator ; 15 import java.util.List ; 16 17 import org.dom4j.Document; 18 import org.dom4j.Element; 19 import org.dom4j.Node; 20 import org.dom4j.io.OutputFormat; 21 import org.dom4j.io.XMLWriter; 22 23 30 public class XPathTool extends SAXDemo { 31 32 protected Document document; 33 34 protected XMLWriter xmlWriter; 35 36 protected boolean verbose; 37 38 public static void main(String [] args) { 39 run(new XPathTool(), args); 40 } 41 42 public XPathTool() { 43 } 44 45 public void run(String [] args) throws Exception { 46 if (args.length < 1) { 47 printUsage("{options} <xml file>"); 48 return; 49 } 50 51 for (int i = 0, size = args.length; i < size; i++) { 52 String arg = args[i]; 53 if (arg.startsWith("-")) { 54 readOptions(arg); 55 } else { 56 println("Parsing: " + arg); 57 document = parse(arg); 58 break; 59 } 60 } 61 62 xmlWriter = new XMLWriter(System.out, new OutputFormat(" ", true)); 63 userLoop(); 64 } 65 66 protected void userLoop() throws Exception { 67 println("Enter XPath expressions to evaluate or 'quit' to stop"); 68 69 BufferedReader reader = new BufferedReader (new InputStreamReader ( 70 System.in)); 71 72 while (true) { 73 print("XPath> "); 74 String line = reader.readLine(); 75 if (line == null) { 76 break; 77 } 78 line = line.trim(); 79 if (line.equalsIgnoreCase("quit")) { 80 break; 81 } 82 evaluateCommand(line); 83 } 84 85 println("Bye"); 86 } 87 88 protected void evaluateCommand(String xpath) throws Exception { 89 println("Results..."); 90 Object results = document.selectObject(xpath); 91 printResult(results); 92 xmlWriter.flush(); 93 } 94 95 protected void printResult(Object results) throws Exception { 96 if (results instanceof Node) { 97 Node node = (Node) results; 98 if (node instanceof Document) { 99 Document document = (Document) node; 100 println("Document: " + document.getName()); 101 } else if (node instanceof Element) { 102 Element element = (Element) node; 103 xmlWriter.writeOpen(element); 104 xmlWriter.println(); 105 } else { 106 xmlWriter.write(node); 107 xmlWriter.println(); 108 } 109 } else if (results instanceof List ) { 110 List list = (List ) results; 111 println("List of " + list.size() + " item(s)"); 112 for (Iterator iter = list.iterator(); iter.hasNext();) { 113 printResult(iter.next()); 114 } 115 } else { 116 if (results == null) { 117 println("null"); 118 } else { 119 println(results + " (" + results.getClass().getName() + ")"); 120 } 121 } 122 } 123 124 protected void readOptions(String arg) { 125 if (arg.indexOf('v') >= 0) { 126 verbose = true; 127 } 128 } 129 } 130 131 169 | Popular Tags |