KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ApplyXPathDOM


1 /*
2  * Copyright 2002-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$
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.domapi.XPathEvaluatorImpl;
32 import org.w3c.dom.Document JavaDoc;
33 import org.w3c.dom.Node JavaDoc;
34 import org.w3c.dom.xpath.XPathEvaluator;
35 import org.w3c.dom.xpath.XPathNSResolver;
36 import org.w3c.dom.xpath.XPathResult;
37 import org.xml.sax.InputSource JavaDoc;
38
39 /**
40  * Very basic utility for applying the DOM L3 XPath API (currently in Last Call)
41  * to an xml file and printing information about the execution of the XPath object
42  * and the nodes it finds.
43  * Takes 2 arguments:
44  * (1) an xml filename
45  * (2) an XPath expression to apply to the file
46  * Examples:
47  * java ApplyXPathDOM foo.xml /
48  * java ApplyXPathDOM foo.xml /doc/name[1]/@last
49  *
50  *<p>See also the <a HREF='http://www.w3.org/TR/2002/WD-DOM-Level-3-XPath-20020328'>Document Object Model (DOM) Level 3 XPath Specification</a>.</p>
51  * @see XPathEvaluator
52  *
53  */

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

153
Popular Tags