KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ApplyXPath


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 /*
17  * $Id: ApplyXPath.java,v 1.21 2004/02/17 19:01:47 minchau Exp $
18  */

19 // This file uses 4 space indents, no tabs.
20

21 import java.io.FileInputStream JavaDoc;
22 import java.io.OutputStreamWriter JavaDoc;
23
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import javax.xml.transform.OutputKeys JavaDoc;
26 import javax.xml.transform.Transformer JavaDoc;
27 import javax.xml.transform.TransformerFactory JavaDoc;
28 import javax.xml.transform.dom.DOMSource JavaDoc;
29 import javax.xml.transform.stream.StreamResult JavaDoc;
30
31 import org.apache.xpath.XPathAPI;
32 import org.w3c.dom.Document JavaDoc;
33 import org.w3c.dom.Node JavaDoc;
34 import org.w3c.dom.traversal.NodeIterator;
35 import org.xml.sax.InputSource JavaDoc;
36
37 /**
38  * Very basic utility for applying an XPath epxression to an xml file and printing information
39  / about the execution of the XPath object and the nodes it finds.
40  * Takes 2 arguments:
41  * (1) an xml filename
42  * (2) an XPath expression to apply to the file
43  * Examples:
44  * java ApplyXPath foo.xml /
45  * java ApplyXPath foo.xml /doc/name[1]/@last
46  * @see XPathAPI
47  */

48 public class ApplyXPath
49 {
50   protected String JavaDoc filename = null;
51   protected String JavaDoc xpath = null;
52
53   /** Process input args and execute the XPath. */
54   public void doMain(String JavaDoc[] args)
55     throws Exception JavaDoc
56   {
57     filename = args[0];
58     xpath = args[1];
59
60     if ((filename != null) && (filename.length() > 0)
61         && (xpath != null) && (xpath.length() > 0))
62     {
63       // Tell that we're loading classes and parsing, so the time it
64
// takes to do this doesn't get confused with the time to do
65
// the actual query and serialization.
66
System.out.println("Loading classes, parsing "+filename+", and setting up serializer");
67       
68       // Set up a DOM tree to query.
69
InputSource JavaDoc in = new InputSource JavaDoc(new FileInputStream JavaDoc(filename));
70       DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
71       dfactory.setNamespaceAware(true);
72       Document JavaDoc doc = dfactory.newDocumentBuilder().parse(in);
73       
74       // Set up an identity transformer to use as serializer.
75
Transformer JavaDoc serializer = TransformerFactory.newInstance().newTransformer();
76       serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
77
78       // Use the simple XPath API to select a nodeIterator.
79
System.out.println("Querying DOM using "+xpath);
80       NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath);
81
82       // Serialize the found nodes to System.out.
83
System.out.println("<output>");
84                   
85       Node JavaDoc n;
86       while ((n = nl.nextNode())!= null)
87       {
88     if (isTextNode(n)) {
89         // DOM may have more than one node corresponding to a
90
// single XPath text node. Coalesce all contiguous text nodes
91
// at this level
92
StringBuffer JavaDoc sb = new StringBuffer JavaDoc(n.getNodeValue());
93         for (
94           Node JavaDoc nn = n.getNextSibling();
95           isTextNode(nn);
96           nn = nn.getNextSibling()
97         ) {
98           sb.append(nn.getNodeValue());
99         }
100         System.out.print(sb);
101     }
102     else {
103          serializer.transform(new DOMSource JavaDoc(n), new StreamResult JavaDoc(new OutputStreamWriter JavaDoc(System.out)));
104     }
105         System.out.println();
106       }
107       System.out.println("</output>");
108     }
109     else
110     {
111       System.out.println("Bad input args: " + filename + ", " + xpath);
112     }
113   }
114   
115   /** Decide if the node is text, and so must be handled specially */
116   static boolean isTextNode(Node JavaDoc n) {
117     if (n == null)
118       return false;
119     short nodeType = n.getNodeType();
120     return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE;
121   }
122
123   /** Main method to run from the command line. */
124   public static void main (String JavaDoc[] args)
125     throws Exception JavaDoc
126   {
127     if (args.length != 2)
128     {
129       System.out.println("java ApplyXPath filename.xml xpath\n"
130                          + "Reads filename.xml and applies the xpath; prints the nodelist found.");
131       return;
132     }
133         
134     ApplyXPath app = new ApplyXPath();
135     app.doMain(args);
136   }
137   
138 } // end of class ApplyXPath
139

140
Popular Tags