KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > GetElementsByTagName


1 /*
2  * Copyright 1999-2002,2004,2005 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 package dom;
18
19 import java.io.PrintWriter JavaDoc;
20
21 import org.w3c.dom.Attr JavaDoc;
22 import org.w3c.dom.Document JavaDoc;
23 import org.w3c.dom.Element JavaDoc;
24 import org.w3c.dom.NamedNodeMap JavaDoc;
25 import org.w3c.dom.NodeList JavaDoc;
26 import org.xml.sax.SAXException JavaDoc;
27 import org.xml.sax.SAXParseException JavaDoc;
28
29 /**
30  * A sample DOM filter. This sample program illustrates how to
31  * use the Document#getElementsByTagName() method to quickly
32  * and easily locate elements by name.
33  *
34  * @author Jeffrey Rodriguez, IBM
35  * @author Andy Clark, IBM
36  *
37  * @version $Id: GetElementsByTagName.java,v 1.11 2005/05/09 00:38:01 mrglavas Exp $
38  */

39 public class GetElementsByTagName {
40
41     //
42
// Constants
43
//
44

45     // feature ids
46

47     /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
48     protected static final String JavaDoc NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
49
50     /** Validation feature id (http://xml.org/sax/features/validation). */
51     protected static final String JavaDoc VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
52
53     /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
54     protected static final String JavaDoc SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
55
56     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
57     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
58     
59     /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations). */
60     protected static final String JavaDoc VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations";
61     
62     /** Dynamic validation feature id (http://apache.org/xml/features/validation/dynamic). */
63     protected static final String JavaDoc DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic";
64     
65     /** XInclude feature id (http://apache.org/xml/features/xinclude). */
66     protected static final String JavaDoc XINCLUDE_FEATURE_ID = "http://apache.org/xml/features/xinclude";
67     
68     /** XInclude fixup base URIs feature id (http://apache.org/xml/features/xinclude/fixup-base-uris). */
69     protected static final String JavaDoc XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-base-uris";
70     
71     /** XInclude fixup language feature id (http://apache.org/xml/features/xinclude/fixup-language). */
72     protected static final String JavaDoc XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-language";
73
74     // default settings
75

76     /** Default parser name (dom.wrappers.Xerces). */
77     protected static final String JavaDoc DEFAULT_PARSER_NAME = "dom.wrappers.Xerces";
78
79     /** Default element name (*). */
80     protected static final String JavaDoc DEFAULT_ELEMENT_NAME = "*";
81
82     /** Default namespaces support (true). */
83     protected static final boolean DEFAULT_NAMESPACES = true;
84
85     /** Default validation support (false). */
86     protected static final boolean DEFAULT_VALIDATION = false;
87
88     /** Default Schema validation support (false). */
89     protected static final boolean DEFAULT_SCHEMA_VALIDATION = false;
90
91     /** Default Schema full checking support (false). */
92     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
93     
94     /** Default validate schema annotations (false). */
95     protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false;
96     
97     /** Default dynamic validation support (false). */
98     protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false;
99     
100     /** Default XInclude processing support (false). */
101     protected static final boolean DEFAULT_XINCLUDE = false;
102     
103     /** Default XInclude fixup base URIs support (true). */
104     protected static final boolean DEFAULT_XINCLUDE_FIXUP_BASE_URIS = true;
105     
106     /** Default XInclude fixup language support (true). */
107     protected static final boolean DEFAULT_XINCLUDE_FIXUP_LANGUAGE = true;
108
109     //
110
// Public static methods
111
//
112

113     /** Prints the specified elements in the given document. */
114     public static void print(PrintWriter JavaDoc out, Document JavaDoc document,
115                              String JavaDoc elementName, String JavaDoc attributeName) {
116
117         // get elements that match
118
NodeList JavaDoc elements = document.getElementsByTagName(elementName);
119
120         // is there anything to do?
121
if (elements == null) {
122             return;
123         }
124
125         // print all elements
126
if (attributeName == null) {
127             int elementCount = elements.getLength();
128             for (int i = 0; i < elementCount; i++) {
129                 Element JavaDoc element = (Element JavaDoc)elements.item(i);
130                 print(out, element, element.getAttributes());
131             }
132         }
133
134         // print elements with given attribute name
135
else {
136             int elementCount = elements.getLength();
137             for (int i = 0; i < elementCount; i++) {
138                 Element JavaDoc element = (Element JavaDoc)elements.item(i);
139                 NamedNodeMap JavaDoc attributes = element.getAttributes();
140                 if (attributes.getNamedItem(attributeName) != null) {
141                     print(out, element, attributes);
142                 }
143             }
144         }
145
146     } // print(PrintWriter,Document,String,String)
147

148     //
149
// Protected static methods
150
//
151

152     /** Prints the specified element. */
153     protected static void print(PrintWriter JavaDoc out,
154                                 Element JavaDoc element, NamedNodeMap JavaDoc attributes) {
155
156         out.print('<');
157         out.print(element.getNodeName());
158         if (attributes != null) {
159             int attributeCount = attributes.getLength();
160             for (int i = 0; i < attributeCount; i++) {
161                 Attr JavaDoc attribute = (Attr JavaDoc)attributes.item(i);
162                 out.print(' ');
163                 out.print(attribute.getNodeName());
164                 out.print("=\"");
165                 out.print(normalize(attribute.getNodeValue()));
166                 out.print('"');
167             }
168         }
169         out.println('>');
170         out.flush();
171
172     } // print(PrintWriter,Element,NamedNodeMap)
173

174     /** Normalizes the given string. */
175     protected static String JavaDoc normalize(String JavaDoc s) {
176         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
177
178         int len = (s != null) ? s.length() : 0;
179         for (int i = 0; i < len; i++) {
180             char ch = s.charAt(i);
181             switch (ch) {
182             case '<': {
183                     str.append("&lt;");
184                     break;
185                 }
186             case '>': {
187                     str.append("&gt;");
188                     break;
189                 }
190             case '&': {
191                     str.append("&amp;");
192                     break;
193                 }
194             case '"': {
195                     str.append("&quot;");
196                     break;
197                 }
198             case '\r':
199             case '\n': {
200                     str.append("&#");
201                     str.append(Integer.toString(ch));
202                     str.append(';');
203                     break;
204                 }
205             default: {
206                     str.append(ch);
207                 }
208             }
209         }
210
211         return str.toString();
212
213     } // normalize(String):String
214

215     //
216
// MAIN
217
//
218

219     /** Main program entry point. */
220     public static void main(String JavaDoc argv[]) {
221
222         // is there anything to do?
223
if (argv.length == 0) {
224             printUsage();
225             System.exit(1);
226         }
227
228         // variables
229
Counter counter = new Counter();
230         PrintWriter JavaDoc out = new PrintWriter JavaDoc(System.out);
231         ParserWrapper parser = null;
232         String JavaDoc elementName = DEFAULT_ELEMENT_NAME;
233         String JavaDoc attributeName = null;
234         boolean namespaces = DEFAULT_NAMESPACES;
235         boolean validation = DEFAULT_VALIDATION;
236         boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
237         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
238         boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
239         boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
240         boolean xincludeProcessing = DEFAULT_XINCLUDE;
241         boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
242         boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
243
244         // process arguments
245
for (int i = 0; i < argv.length; i++) {
246             String JavaDoc arg = argv[i];
247             if (arg.startsWith("-")) {
248                 String JavaDoc option = arg.substring(1);
249                 if (option.equals("p")) {
250                     // get parser name
251
if (++i == argv.length) {
252                         System.err.println("error: Missing argument to -p option.");
253                     }
254                     String JavaDoc parserName = argv[i];
255
256                     // create parser
257
try {
258                         parser = (ParserWrapper)Class.forName(parserName).newInstance();
259                     }
260                     catch (Exception JavaDoc e) {
261                         parser = null;
262                         System.err.println("error: Unable to instantiate parser ("+parserName+")");
263                     }
264                     continue;
265                 }
266                 if (option.equals("e")) {
267                     if (++i == argv.length) {
268                         System.err.println("error: Missing argument to -e option.");
269                     }
270                     elementName = argv[i];
271                     continue;
272                 }
273                 if (option.equals("a")) {
274                     if (++i == argv.length) {
275                         System.err.println("error: Missing argument to -a option.");
276                     }
277                     attributeName = argv[i];
278                     continue;
279                 }
280                 if (option.equalsIgnoreCase("n")) {
281                     namespaces = option.equals("n");
282                     continue;
283                 }
284                 if (option.equalsIgnoreCase("v")) {
285                     validation = option.equals("v");
286                     continue;
287                 }
288                 if (option.equalsIgnoreCase("s")) {
289                     schemaValidation = option.equals("s");
290                     continue;
291                 }
292                 if (option.equalsIgnoreCase("f")) {
293                     schemaFullChecking = option.equals("f");
294                     continue;
295                 }
296                 if (option.equalsIgnoreCase("va")) {
297                     validateAnnotations = option.equals("va");
298                     continue;
299                 }
300                 if (option.equalsIgnoreCase("dv")) {
301                     dynamicValidation = option.equals("dv");
302                     continue;
303                 }
304                 if (option.equalsIgnoreCase("xi")) {
305                     xincludeProcessing = option.equals("xi");
306                     continue;
307                 }
308                 if (option.equalsIgnoreCase("xb")) {
309                     xincludeFixupBaseURIs = option.equals("xb");
310                     continue;
311                 }
312                 if (option.equalsIgnoreCase("xl")) {
313                     xincludeFixupLanguage = option.equals("xl");
314                     continue;
315                 }
316                 if (option.equals("h")) {
317                     printUsage();
318                     continue;
319                 }
320             }
321
322             // use default parser?
323
if (parser == null) {
324
325                 // create parser
326
try {
327                     parser = (ParserWrapper)Class.forName(DEFAULT_PARSER_NAME).newInstance();
328                 }
329                 catch (Exception JavaDoc e) {
330                     System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")");
331                     continue;
332                 }
333             }
334
335             // set parser features
336
try {
337                 parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
338             }
339             catch (SAXException JavaDoc e) {
340                 System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")");
341             }
342             try {
343                 parser.setFeature(VALIDATION_FEATURE_ID, validation);
344             }
345             catch (SAXException JavaDoc e) {
346                 System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")");
347             }
348             try {
349                 parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
350             }
351             catch (SAXException JavaDoc e) {
352                 System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")");
353             }
354             try {
355                 parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
356             }
357             catch (SAXException JavaDoc e) {
358                 System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")");
359             }
360             try {
361                 parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
362             }
363             catch (SAXException JavaDoc e) {
364                 System.err.println("warning: Parser does not support feature ("+VALIDATE_ANNOTATIONS_ID+")");
365             }
366             try {
367                 parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
368             }
369             catch (SAXException JavaDoc e) {
370                 System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")");
371             }
372             try {
373                 parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
374             }
375             catch (SAXException JavaDoc e) {
376                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FEATURE_ID+")");
377             }
378             try {
379                 parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
380             }
381             catch (SAXException JavaDoc e) {
382                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")");
383             }
384             try {
385                 parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
386             }
387             catch (SAXException JavaDoc e) {
388                 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")");
389             }
390
391             // parse file
392
try {
393                 Document JavaDoc document = parser.parse(arg);
394                 GetElementsByTagName.print(out, document, elementName, attributeName);
395             }
396             catch (SAXParseException JavaDoc e) {
397                 // ignore
398
}
399             catch (Exception JavaDoc e) {
400                 System.err.println("error: Parse error occurred - "+e.getMessage());
401                 if (e instanceof SAXException JavaDoc) {
402                     Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
403                     if (nested != null) {
404                         e = nested;
405                     }
406                 }
407                 e.printStackTrace(System.err);
408             }
409         }
410
411     } // main(String[])
412

413     //
414
// Private static methods
415
//
416

417     /** Prints the usage. */
418     private static void printUsage() {
419
420         System.err.println("usage: java dom.GetElementsByTagName (options) uri ...");
421         System.err.println();
422
423         System.err.println("options:");
424         System.err.println(" -p name Select parser by name.");
425         System.err.println(" -e name Specify element name for search.");
426         System.err.println(" -a name Specify attribute name for specified elements.");
427         System.err.println(" -n | -N Turn on/off namespace processing.");
428         System.err.println(" -v | -V Turn on/off validation.");
429         System.err.println(" -s | -S Turn on/off Schema validation support.");
430         System.err.println(" NOTE: Not supported by all parsers.");
431         System.err.println(" -f | -F Turn on/off Schema full checking.");
432         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
433         System.err.println(" -va | -VA Turn on/off validation of schema annotations.");
434         System.err.println(" NOTE: Requires use of -s and not supported by all parsers.");
435         System.err.println(" -dv | -DV Turn on/off dynamic validation.");
436         System.err.println(" NOTE: Not supported by all parsers.");
437         System.err.println(" -xi | -XI Turn on/off XInclude processing.");
438         System.err.println(" NOTE: Not supported by all parsers.");
439         System.err.println(" -xb | -XB Turn on/off base URI fixup during XInclude processing.");
440         System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
441         System.err.println(" -xl | -XL Turn on/off language fixup during XInclude processing.");
442         System.err.println(" NOTE: Requires use of -xi and not supported by all parsers.");
443         System.err.println(" -h This help screen.");
444         System.err.println();
445
446         System.err.println("defaults:");
447         System.err.println(" Parser: "+DEFAULT_PARSER_NAME);
448         System.err.println(" Element: "+DEFAULT_ELEMENT_NAME);
449         System.err.print(" Namespaces: ");
450         System.err.println(DEFAULT_NAMESPACES ? "on" : "off");
451         System.err.print(" Validation: ");
452         System.err.println(DEFAULT_VALIDATION ? "on" : "off");
453         System.err.print(" Schema: ");
454         System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off");
455         System.err.print(" Schema full checking: ");
456         System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off");
457         System.err.print(" Dynamic: ");
458         System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off");
459         System.err.print(" XInclude: ");
460         System.err.println(DEFAULT_XINCLUDE ? "on" : "off");
461         System.err.print(" XInclude base URI fixup: ");
462         System.err.println(DEFAULT_XINCLUDE_FIXUP_BASE_URIS ? "on" : "off");
463         System.err.print(" XInclude language fixup: ");
464         System.err.println(DEFAULT_XINCLUDE_FIXUP_LANGUAGE ? "on" : "off");
465
466     } // printUsage()
467

468 } // class GetElementsByTagName
469
Popular Tags