1 import net.sf.saxon.om.NamespaceConstant; 2 import net.sf.saxon.om.NodeInfo; 3 import net.sf.saxon.xpath.XPathEvaluator; 4 import org.xml.sax.InputSource ; 5 6 import javax.xml.namespace.QName ; 7 import javax.xml.transform.sax.SAXSource ; 8 import javax.xml.xpath.*; 9 import java.io.BufferedReader ; 10 import java.io.File ; 11 import java.io.InputStreamReader ; 12 import java.util.Iterator ; 13 import java.util.List ; 14 15 25 26 public class XPathExample implements XPathVariableResolver { 27 28 private String currentWord; 29 30 34 35 public static void main (String args[]) 36 throws Exception 37 { 38 40 if (args.length != 1) { 41 System.err.println("Usage: java XPathExample input-file"); 42 System.exit(1); 43 } 44 XPathExample app = new XPathExample(); 45 app.go(args[0]); 46 } 47 48 51 52 public void go(String filename) throws Exception { 53 54 58 XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); 59 XPath xpe = xpf.newXPath(); 60 System.err.println("Loaded XPath Provider " + xpe.getClass().getName()); 61 62 InputSource is = new InputSource (new File (filename).toURL().toString()); 65 SAXSource ss = new SAXSource (is); 66 NodeInfo doc = ((XPathEvaluator)xpe).setSource(ss); 67 68 xpe.setXPathVariableResolver(this); 70 71 73 XPathExpression findLine = 74 xpe.compile("//LINE[contains(., $word)]"); 75 XPathExpression findLocation = 76 xpe.compile("concat(ancestor::ACT/TITLE, ' ', ancestor::SCENE/TITLE)"); 77 XPathExpression findSpeaker = 78 xpe.compile("string(ancestor::SPEECH/SPEAKER[1])"); 79 80 82 BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); 83 84 86 while (true) { 87 88 System.out.println("\n>>>> Enter a word to search for, or '.' to quit:\n"); 90 91 String word = in.readLine().trim(); 93 if (word.equals(".")) { 94 break; 95 } 96 if (!word.equals("")) { 97 98 currentWord = word; 100 101 List matchedLines = (List )findLine.evaluate(doc, XPathConstants.NODESET); 103 104 boolean found = false; 106 if (matchedLines != null) { 107 for (Iterator iter = matchedLines.iterator(); iter.hasNext();) { 108 109 found = true; 111 112 NodeInfo line = (NodeInfo)iter.next(); 114 115 System.out.println('\n' + findLocation.evaluate(line)); 117 118 System.out.println(findSpeaker.evaluate(line) + ": " + line.getStringValue()); 120 } 121 } 122 123 if (!found) { 125 System.err.println("No lines were found containing the word '" + word + '\''); 126 } 127 } 128 } 129 130 System.out.println("Finished."); 132 } 133 134 139 140 public Object resolveVariable(QName qName) { 141 if (qName.getLocalPart().equals("word")) { 142 return currentWord; 143 } else { 144 return null; 145 } 146 } 147 148 } 149 | Popular Tags |