1 9 10 package org.dom4j.samples; 11 12 import java.util.Iterator ; 13 import java.util.List ; 14 15 import org.dom4j.Document; 16 import org.dom4j.DocumentHelper; 17 import org.dom4j.XPath; 18 19 27 public class XPathGrep extends SAXDemo { 28 29 protected XPath xpath; 30 31 protected boolean verbose; 32 33 public static void main(String [] args) { 34 run(new XPathGrep(), args); 35 } 36 37 public XPathGrep() { 38 } 39 40 public void run(String [] args) throws Exception { 41 if (args.length < 2) { 42 printUsage("{options} <XPath expression> <xml file(s)>"); 43 return; 44 } 45 46 for (int i = 0, size = args.length; i < size; i++) { 47 String arg = args[i]; 48 if (arg.startsWith("-")) { 49 readOptions(arg); 50 } else { 51 if (xpath == null) { 52 setXPath(arg); 53 } else { 54 Document document = parse(arg); 55 process(document); 56 } 57 } 58 } 59 } 60 61 public void setXPath(String xpathExpression) { 62 xpath = DocumentHelper.createXPath(xpathExpression); 63 } 64 65 protected void process(Document document) throws Exception { 66 if (verbose) { 68 println("About to evalute: " + xpath); 69 println("Results:"); 70 } 71 72 Object object = xpath.evaluate(document); 73 74 if (object instanceof List ) { 75 List list = (List ) object; 76 for (Iterator iter = list.iterator(); iter.hasNext();) { 77 getXMLWriter().write(iter.next()); 78 getXMLWriter().println(); 79 } 80 getXMLWriter().flush(); 81 } else { 82 println((object != null) ? object.toString() : "null"); 83 } 84 } 85 86 protected void readOptions(String arg) { 87 if (arg.indexOf('v') >= 0) { 88 verbose = true; 89 } 90 } 91 } 92 93 131 | Popular Tags |