KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ApplyXPathJAXP


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Xalan" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 1999, Lotus
53  * Development Corporation., http://www.lotus.com. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57 // This file uses 4 space indents, no tabs.
58

59 import net.sf.saxon.om.NamespaceConstant;
60 import net.sf.saxon.xpath.XPathEvaluator;
61 import org.jdom.input.SAXBuilder;
62 import org.w3c.dom.Document JavaDoc;
63 import org.xml.sax.InputSource JavaDoc;
64
65 import javax.xml.namespace.NamespaceContext JavaDoc;
66 import javax.xml.namespace.QName JavaDoc;
67 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
68 import javax.xml.transform.OutputKeys JavaDoc;
69 import javax.xml.transform.Transformer JavaDoc;
70 import javax.xml.transform.TransformerFactory JavaDoc;
71 import javax.xml.transform.stream.StreamSource JavaDoc;
72 import javax.xml.xpath.*;
73 import java.io.File JavaDoc;
74 import java.io.FileInputStream JavaDoc;
75 import java.util.Iterator JavaDoc;
76 import java.util.List JavaDoc;
77
78
79 /**
80  * Very basic utility for applying the XPath API in JAXP 1.3
81  * to an xml file and printing information about the execution of the XPath object
82  * and the nodes it finds.
83  * Takes 2 or 3 arguments:
84  * (1) an xml filename
85  * (2) an XPath expression to apply to the file
86  * (3) (optionally) short name of the object model to be used: "saxon" | "dom" | "jdom" | "xom"
87  * Examples:
88  * java ApplyXPathJAXP foo.xml /
89  * java ApplyXPathJAXP foo.xml /doc/name[1]/@last
90  * <p/>
91  * This version modified by Michael Kay to allow testing of additional
92  * features of the interface.
93  *
94  * The XPath expression may use:
95  * (a) A namespace prefix f which is bound to the namespace http://localhost/f
96  * (b) A variable $f:pi whose value is the Double pi
97  * (c) A function f:sqrt(x) that calculates the square root of its argument x
98  *
99  * @see javax.xml.xpath.XPath
100  */

101 public class ApplyXPathJAXP {
102     protected String JavaDoc filename = null;
103     protected String JavaDoc xpathExpressionStr = null;
104     protected String JavaDoc objectModel = null;
105
106     /**
107      * Process input args and execute the XPath.
108      */

109     public void doMain(String JavaDoc[] args)
110             throws Exception JavaDoc {
111         filename = args[0];
112         xpathExpressionStr = args[1];
113         String JavaDoc om = "saxon";
114         if (args.length > 2) {
115             om = args[2];
116         }
117         if (om.equals("saxon")) {
118             objectModel = NamespaceConstant.OBJECT_MODEL_SAXON;
119         } else if (om.equals("dom")) {
120             objectModel = XPathConstants.DOM_OBJECT_MODEL;
121         } else if (om.equals("jdom")) {
122             objectModel = NamespaceConstant.OBJECT_MODEL_JDOM;
123         } else if (om.equals("xom")) {
124             objectModel = NamespaceConstant.OBJECT_MODEL_XOM;
125         } else {
126             System.err.println("Unknown object model " + args[2]);
127             return;
128         }
129
130         if ((filename != null) && (filename.length() > 0)
131                 && (xpathExpressionStr != null) && (xpathExpressionStr.length() > 0)) {
132             // Tell that we're loading classes and parsing, so the time it
133
// takes to do this doesn't get confused with the time to do
134
// the actual query and serialization.
135
System.out.println("Loading classes, parsing " + filename + ", and setting up serializer");
136
137             Object JavaDoc document = null;
138             if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_SAXON)) {
139                 document = new XPathEvaluator().setSource(new StreamSource JavaDoc(new File JavaDoc(filename)));
140
141             } else if (objectModel.equals(XPathConstants.DOM_OBJECT_MODEL)) {
142                 InputSource JavaDoc in = new InputSource JavaDoc(new FileInputStream JavaDoc(filename));
143                 DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
144                 dfactory.setNamespaceAware(true);
145                 Document JavaDoc doc = dfactory.newDocumentBuilder().parse(in);
146                 document = doc;
147
148             } else if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_JDOM)) {
149                 InputSource JavaDoc in = new InputSource JavaDoc(new FileInputStream JavaDoc(filename));
150                 SAXBuilder builder = new SAXBuilder();
151                 document = builder.build(in);
152
153             } else if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_XOM)) {
154                 nu.xom.Builder builder = new nu.xom.Builder();
155                 document = builder.build(new FileInputStream JavaDoc(filename));
156             }
157
158             // Set up an identity transformer to use as serializer.
159
Transformer JavaDoc serializer = TransformerFactory.newInstance().newTransformer();
160             serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
161
162             // Use the JAXP 1.3 XPath API to apply the xpath expression to the doc.
163
System.out.println("Querying " + om + " using " + xpathExpressionStr);
164
165             // Following is specific to Saxon: should be in a properties file
166
System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_SAXON,
167                     "net.sf.saxon.xpath.XPathFactoryImpl");
168             System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
169                     "net.sf.saxon.xpath.XPathFactoryImpl");
170             System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_JDOM,
171                     "net.sf.saxon.xpath.XPathFactoryImpl");
172             System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_XOM,
173                     "net.sf.saxon.xpath.XPathFactoryImpl");
174
175             // Get a instance of XPathFactory with ObjectModel URL parameter. If no parameter
176
// is mentioned then default DOM Object Model is used
177
XPathFactory xpathFactory = XPathFactory.newInstance(objectModel);
178             XPath xpath = xpathFactory.newXPath();
179
180             // Declare a namespace context:
181
xpath.setNamespaceContext(
182                     new NamespaceContext JavaDoc() {
183                         public String JavaDoc getNamespaceURI(String JavaDoc s) {
184                             if (s.equals("f")) {
185                                 return "http://localhost/f";
186                             } else {
187                                 return null;
188                             }
189                         }
190
191                         public String JavaDoc getPrefix(String JavaDoc s) { return null; }
192
193                         public Iterator JavaDoc getPrefixes(String JavaDoc s) { return null; }
194                     }
195                 );
196
197             // Declare a variable:
198

199             final QName JavaDoc f_var = new QName JavaDoc("http://localhost/f", "pi");
200             xpath.setXPathVariableResolver(
201                     new XPathVariableResolver() {
202                         public Object JavaDoc resolveVariable(QName JavaDoc qName) {
203                             if (qName.equals(f_var)) {
204                                 return new Double JavaDoc(Math.PI);
205                             } else {
206                                 return null;
207                             }
208                         }
209                     }
210                 );
211
212             // Declare a function:
213

214             final XPathFunction sqrt = new XPathFunction() {
215                 public Object JavaDoc evaluate(List JavaDoc list) throws XPathFunctionException {
216                     Object JavaDoc arg = list.get(0);
217                     if (!(arg instanceof Double JavaDoc)) {
218                         throw new XPathFunctionException("f:sqrt() expects an xs:double argument");
219                     }
220                     return new Double JavaDoc(Math.sqrt(((Double JavaDoc)arg).doubleValue()));
221                 }
222             };
223
224             final QName JavaDoc f_sqrt = new QName JavaDoc("http://localhost/f", "sqrt");
225             xpath.setXPathFunctionResolver(
226                     new XPathFunctionResolver() {
227                         public XPathFunction resolveFunction(QName JavaDoc qName, int arity) {
228                             if (qName.equals(f_sqrt) && arity==1) {
229                                 return sqrt;
230                             } else {
231                                 return null;
232                             }
233                         }
234                     }
235                 );
236
237
238             // Now compile the expression
239
XPathExpression xpathExpression = xpath.compile(xpathExpressionStr);
240
241
242             // Now evaluate the expression on the document to get String result
243
String JavaDoc resultString = xpathExpression.evaluate(document);
244
245             // Serialize the found nodes to System.out.
246
System.out.println("<output>");
247             System.out.println("String Value => " + resultString);
248             System.out.println("</output>");
249         } else {
250             System.out.println("Bad input args: " + filename + ", " + xpathExpressionStr);
251         }
252     }
253
254
255     /**
256      * Main method to run from the command line.
257      */

258     public static void main(String JavaDoc[] args)
259             throws Exception JavaDoc {
260         if (args.length != 2 && args.length != 3) {
261             System.out.println("java ApplyXPathJAXP filename.xml xpath [saxon|dom|jdom|xom]\n"
262                     + "Reads filename.xml and applies the xpath; prints the String value of result.");
263             return;
264         }
265
266         ApplyXPathJAXP app = new ApplyXPathJAXP();
267         app.doMain(args);
268     }
269
270 } // end of class ApplyXPathJAXP
271

272
Popular Tags