StandaloneContext sc = (StandaloneContext)xpe.getStaticContext();
Variable wordVar = sc.declareVariable("word", "");
// Compile the XPath expressions used by the application
XPathExpression findLine =
xpe.createExpression("//LINE[contains(., $word)]");
XPathExpression findLocation =
xpe.createExpression("concat(ancestor::ACT/TITLE, ' ', ancestor::SCENE/TITLE)");
XPathExpression findSpeaker =
xpe.createExpression("string(ancestor::SPEECH/SPEAKER[1])");
// Create a reader for reading input from the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Loop until the user enters "." to end the application
while (true) {
// Prompt for input
System.out.println("\n>>>> Enter a word to search for, or '.' to quit:\n");
// Read the input
String word = in.readLine().trim();
if (word.equals(".")) {
break;
}
if (!word.equals("")) {
// Set the value of the XPath variable
wordVar.setValue(word);
// Find the lines containing the requested word
List matchedLines = findLine.evaluate();
// Process these lines
boolean found = false;
for (Iterator iter = matchedLines.iterator(); iter.hasNext();) {
// Note that we have found at least one line
found = true;
// Get the next matching line
NodeInfo line = (NodeInfo)iter.next();
// Find where it appears in the play
findLocation.setContextNode(line);
System.out.println("\n" + findLocation.evaluateSingle());
// Find out who the speaker of this line is
findSpeaker.setContextNode(line);
// Output the name of the speaker and the content of the line
System.out.println(findSpeaker.evaluateSingle() + ": " + line.getStringValue());
}
// If no lines were found, say so
if (!found) {
System.err.println("No lines were found containing the word '" + word + "'");