KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > DOMFilter


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999, 2000 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 "Xerces" 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, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package dom;
59
60 import org.w3c.dom.Attr JavaDoc;
61 import org.w3c.dom.Document JavaDoc;
62 import org.w3c.dom.Element JavaDoc;
63 import org.w3c.dom.NamedNodeMap JavaDoc;
64 import org.w3c.dom.NodeList JavaDoc;
65
66 import util.Arguments;
67
68
69 /**
70  * A sample DOM filter. This sample program illustrates how to
71  * use the Document#getElementsByTagName() method to quickly
72  * and easily locate elements by name.
73  *
74  * @version $Id: DOMFilter.java,v 1.2 2005/01/26 08:28:44 jkjome Exp $
75  */

76 public class DOMFilter {
77
78     //
79
// Constants
80
//
81

82     /** Default parser name. */
83     private static final String JavaDoc
84     DEFAULT_PARSER_NAME = "dom.wrappers.DOMParser";
85
86     private static boolean setValidation = false; //defaults
87
private static boolean setNameSpaces = true;
88     private static boolean setSchemaSupport = true;
89     private static boolean setSchemaFullSupport = false;
90     private static boolean setDeferredDOM = true;
91
92
93
94     //
95
// Public static methods
96
//
97

98     /** Prints the specified elements in the given document. */
99     public static void print(String JavaDoc parserWrapperName, String JavaDoc uri,
100                              String JavaDoc elementName, String JavaDoc attributeName) {
101
102         try {
103             // parse document
104
DOMParserWrapper parser =
105             (DOMParserWrapper)Class.forName(parserWrapperName).newInstance();
106
107             parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion",
108                                setDeferredDOM );
109             parser.setFeature( "http://xml.org/sax/features/validation",
110                                setValidation );
111             parser.setFeature( "http://xml.org/sax/features/namespaces",
112                                setNameSpaces );
113             parser.setFeature( "http://apache.org/xml/features/validation/schema",
114                                setSchemaSupport );
115             parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking",
116                                setSchemaFullSupport );
117
118
119             Document JavaDoc document = parser.parse(uri);
120
121             // get elements that match
122
NodeList JavaDoc elements = document.getElementsByTagName(elementName);
123
124             // print nodes
125
print(elements, attributeName);
126         } catch (Exception JavaDoc e) {
127             e.printStackTrace(System.err);
128         }
129
130     } // print(String,String,String,String)
131

132     //
133
// Private static methods
134
//
135

136     /**
137      * Prints the contents of the given element node list. If the given
138      * attribute name is non-null, then all of the elements are printed
139      * out
140      */

141     private static void print(NodeList JavaDoc elements, String JavaDoc attributeName) {
142
143         // is there anything to do?
144
if (elements == null) {
145             return;
146         }
147
148         // print all elements
149
if (attributeName == null) {
150             int elementCount = elements.getLength();
151             for (int i = 0; i < elementCount; i++) {
152                 Element JavaDoc element = (Element JavaDoc)elements.item(i);
153                 print(element, element.getAttributes());
154             }
155         }
156
157         // print elements with given attribute name
158
else {
159             int elementCount = elements.getLength();
160             for (int i = 0; i < elementCount; i++) {
161                 Element JavaDoc element = (Element JavaDoc)elements.item(i);
162                 NamedNodeMap JavaDoc attributes = element.getAttributes();
163                 if (attributes.getNamedItem(attributeName) != null) {
164                     print(element, attributes);
165                 }
166             }
167         }
168
169     } // print(NodeList,String)
170

171     /** Prints the specified element. */
172     private static void print(Element JavaDoc element, NamedNodeMap JavaDoc attributes) {
173
174         System.out.print('<');
175         System.out.print(element.getNodeName());
176         if (attributes != null) {
177             int attributeCount = attributes.getLength();
178             for (int i = 0; i < attributeCount; i++) {
179                 Attr JavaDoc attribute = (Attr JavaDoc)attributes.item(i);
180                 System.out.print(' ');
181                 System.out.print(attribute.getNodeName());
182                 System.out.print("=\"");
183                 System.out.print(normalize(attribute.getNodeValue()));
184                 System.out.print('"');
185             }
186         }
187         System.out.println('>');
188
189     } // print(Element,NamedNodeMap)
190

191     /** Normalizes the given string. */
192     private static String JavaDoc normalize(String JavaDoc s) {
193         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
194
195         int len = (s != null) ? s.length() : 0;
196         for (int i = 0; i < len; i++) {
197             char ch = s.charAt(i);
198             switch (ch) {
199             case '<': {
200                     str.append("&lt;");
201                     break;
202                 }
203             case '>': {
204                     str.append("&gt;");
205                     break;
206                 }
207             case '&': {
208                     str.append("&amp;");
209                     break;
210                 }
211             case '"': {
212                     str.append("&quot;");
213                     break;
214                 }
215             case '\r':
216             case '\n': {
217                     str.append("&#");
218                     str.append(Integer.toString(ch));
219                     str.append(';');
220                     break;
221                 }
222             default: {
223                     str.append(ch);
224                 }
225             }
226         }
227
228         return str.toString();
229
230     } // normalize(String):String
231

232     //
233
// Main
234
//
235

236     /** Main program entry point. */
237     public static void main(String JavaDoc argv[]) {
238
239         Arguments argopt = new Arguments();
240         argopt.setUsage( new String JavaDoc[]
241                          { "usage: java dom.DOMFilter (options) uri ...","",
242                              "options:",
243                              " -p name Specify DOM parser wrapper by name.",
244                              " -e name Specify element name to search for. Default is \"*\".",
245                              " -a name Specify attribute name of specified elements.",
246                              " -p name Specify DOM parser wrapper by name.",
247                              " -n | -N Turn on/off namespace [default=on]",
248                              " -v | -V Turn on/off validation [default=on]",
249                              " -s | -S Turn on/off Schema support [default=on]",
250                              " -f | -F Turn on/off Schema full consraint checking [default=off]",
251                              " -d | -D Turn on/off deferred DOM [default=on]",
252                              " -h This help screen."} );
253
254         // is there anything to do?
255
if (argv.length == 0) {
256             argopt.printUsage();
257             System.exit(1);
258         }
259
260         // vars
261
String JavaDoc parserName = DEFAULT_PARSER_NAME;
262         String JavaDoc elementName = "*"; // all elements
263
String JavaDoc attributeName = null;
264
265
266         /////
267

268         argopt.parseArgumentTokens(argv , new char[] { 'p', 'e', 'a'} );
269         int c;
270         String JavaDoc arg = null;
271         while ( ( arg = argopt.getlistFiles() ) != null ) {
272 outer:
273             while ( (c = argopt.getArguments()) != -1 ){
274                 switch (c) {
275                 case 'v':
276                     setValidation = true;
277                     break;
278                 case 'V':
279                     setValidation = false;
280                     break;
281                 case 'N':
282                     setNameSpaces = false;
283                     break;
284                 case 'n':
285                     setNameSpaces = true;
286                     break;
287                 case 'p':
288                     parserName = argopt.getStringParameter();
289                     break;
290                 case 'd':
291                     setDeferredDOM = true;
292                     break;
293                 case 'D':
294                     setDeferredDOM = false;
295                     break;
296                 case 's':
297                     setSchemaSupport = true;
298                     break;
299                 case 'S':
300                     setSchemaSupport = false;
301                     break;
302                 case 'e':
303                     elementName = argopt.getStringParameter();
304                     break;
305                 case 'a':
306                     attributeName = argopt.getStringParameter();
307                     break;
308                 case 'f':
309                     setSchemaFullSupport = true;
310                     break;
311                 case 'F':
312                     setSchemaFullSupport = false;
313                     break;
314                 case '?':
315                 case 'h':
316                 case '-':
317                     argopt.printUsage();
318                     System.exit(1);
319                     break;
320                 case -1:
321                     break outer;
322                 default:
323                     break;
324                 }
325             }
326             // print uri
327
System.err.println(arg+':');
328             print(parserName, arg, elementName, attributeName);
329         }
330     } // main(String[])
331

332 } // class DOMFilter
333

334
Popular Tags