KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > XPathExample


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 JavaDoc;
5
6 import javax.xml.namespace.QName JavaDoc;
7 import javax.xml.transform.sax.SAXSource JavaDoc;
8 import javax.xml.xpath.*;
9 import java.io.BufferedReader JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.List JavaDoc;
14
15 /**
16   * Class XPathExample:
17   * This class illustrates the use of the JAXP XPath API. It is a simple command-line application,
18   * which prompts the user for a word, and replies with a list of all the lines containing that
19   * word within a Shakespeare play.
20   *
21   *
22   * @author Michael H. Kay (Michael.H.Kay@ntlworld.com)
23   * @version October 2004: rewritten to use the JAXP API
24   */

25
26 public class XPathExample implements XPathVariableResolver {
27
28     private String JavaDoc currentWord;
29
30     /**
31       * main()<BR>
32       * Expects one argument, the input filename<BR>
33       */

34
35     public static void main (String JavaDoc args[])
36     throws Exception JavaDoc
37     {
38         // Check the command-line arguments
39

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     /**
49     * Run the application
50     */

51
52     public void go(String JavaDoc filename) throws Exception JavaDoc {
53
54         // Following is specific to Saxon: should be in a properties file
55
// System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_SAXON,
56
// "net.sf.saxon.xpath.XPathFactoryImpl");
57

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         // Build the source document. This is outside the scope of the XPath API, and
63
// is therefore Saxon-specific.
64
InputSource JavaDoc is = new InputSource JavaDoc(new File JavaDoc(filename).toURL().toString());
65         SAXSource JavaDoc ss = new SAXSource JavaDoc(is);
66         NodeInfo doc = ((XPathEvaluator)xpe).setSource(ss);
67
68         // Declare a variable resolver to return the value of variables used in XPath expressions
69
xpe.setXPathVariableResolver(this);
70
71         // Compile the XPath expressions used by the application
72

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         // Create a reader for reading input from the console
81

82         BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
83
84         // Loop until the user enters "." to end the application
85

86         while (true) {
87
88             // Prompt for input
89
System.out.println("\n>>>> Enter a word to search for, or '.' to quit:\n");
90
91             // Read the input
92
String JavaDoc word = in.readLine().trim();
93             if (word.equals(".")) {
94                 break;
95             }
96             if (!word.equals("")) {
97
98                 // Set the value of the XPath variable
99
currentWord = word;
100
101                 // Find the lines containing the requested word
102
List JavaDoc matchedLines = (List JavaDoc)findLine.evaluate(doc, XPathConstants.NODESET);
103
104                 // Process these lines
105
boolean found = false;
106                 if (matchedLines != null) {
107                     for (Iterator JavaDoc iter = matchedLines.iterator(); iter.hasNext();) {
108
109                         // Note that we have found at least one line
110
found = true;
111
112                         // Get the next matching line
113
NodeInfo line = (NodeInfo)iter.next();
114
115                         // Find where it appears in the play
116
System.out.println('\n' + findLocation.evaluate(line));
117
118                         // Output the name of the speaker and the content of the line
119
System.out.println(findSpeaker.evaluate(line) + ": " + line.getStringValue());
120                     }
121                 }
122
123                 // If no lines were found, say so
124
if (!found) {
125                     System.err.println("No lines were found containing the word '" + word + '\'');
126                 }
127             }
128         }
129
130         // Finish when the user enters "."
131
System.out.println("Finished.");
132     }
133
134     /**
135      * This class serves as a variable resolver. The only variable used is $word.
136      * @param qName the name of the variable required
137      * @return the current value of the variable
138      */

139
140     public Object JavaDoc resolveVariable(QName JavaDoc qName) {
141         if (qName.getLocalPart().equals("word")) {
142             return currentWord;
143         } else {
144             return null;
145         }
146     }
147
148 }
149
Popular Tags