1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package dom; 19 20 import java.io.PrintWriter; 21 22 import org.w3c.dom.Attr; 23 import org.w3c.dom.Document; 24 import org.w3c.dom.Element; 25 import org.w3c.dom.NamedNodeMap; 26 import org.w3c.dom.NodeList; 27 import org.xml.sax.SAXException; 28 import org.xml.sax.SAXParseException; 29 30 /** 31 * A sample DOM filter. This sample program illustrates how to 32 * use the Document#getElementsByTagName() method to quickly 33 * and easily locate elements by name. 34 * 35 * @author Jeffrey Rodriguez, IBM 36 * @author Andy Clark, IBM 37 * 38 * @version $Id: GetElementsByTagName.java 447683 2006-09-19 02:36:31Z mrglavas $ 39 */ 40 public class GetElementsByTagName { 41 42 // 43 // Constants 44 // 45 46 // feature ids 47 48 /** Namespaces feature id (http://xml.org/sax/features/namespaces). */ 49 protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces"; 50 51 /** Validation feature id (http://xml.org/sax/features/validation). */ 52 protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation"; 53 54 /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */ 55 protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema"; 56 57 /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ 58 protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; 59 60 /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */ 61 protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations"; 62 63 /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations). */ 64 protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations"; 65 66 /** Dynamic validation feature id (http://apache.org/xml/features/validation/dynamic). */ 67 protected static final String DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic"; 68 69 /** XInclude feature id (http://apache.org/xml/features/xinclude). */ 70 protected static final String XINCLUDE_FEATURE_ID = "http://apache.org/xml/features/xinclude"; 71 72 /** XInclude fixup base URIs feature id (http://apache.org/xml/features/xinclude/fixup-base-uris). */ 73 protected static final String XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-base-uris"; 74 75 /** XInclude fixup language feature id (http://apache.org/xml/features/xinclude/fixup-language). */ 76 protected static final String XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID = "http://apache.org/xml/features/xinclude/fixup-language"; 77 78 // default settings 79 80 /** Default parser name (dom.wrappers.Xerces). */ 81 protected static final String DEFAULT_PARSER_NAME = "dom.wrappers.Xerces"; 82 83 /** Default element name (*). */ 84 protected static final String DEFAULT_ELEMENT_NAME = "*"; 85 86 /** Default namespaces support (true). */ 87 protected static final boolean DEFAULT_NAMESPACES = true; 88 89 /** Default validation support (false). */ 90 protected static final boolean DEFAULT_VALIDATION = false; 91 92 /** Default Schema validation support (false). */ 93 protected static final boolean DEFAULT_SCHEMA_VALIDATION = false; 94 95 /** Default Schema full checking support (false). */ 96 protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false; 97 98 /** Default honour all schema locations (false). */ 99 protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false; 100 101 /** Default validate schema annotations (false). */ 102 protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false; 103 104 /** Default dynamic validation support (false). */ 105 protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false; 106 107 /** Default XInclude processing support (false). */ 108 protected static final boolean DEFAULT_XINCLUDE = false; 109 110 /** Default XInclude fixup base URIs support (true). */ 111 protected static final boolean DEFAULT_XINCLUDE_FIXUP_BASE_URIS = true; 112 113 /** Default XInclude fixup language support (true). */ 114 protected static final boolean DEFAULT_XINCLUDE_FIXUP_LANGUAGE = true; 115 116 // 117 // Public static methods 118 // 119 120 /** Prints the specified elements in the given document. */ 121 public static void print(PrintWriter out, Document document, 122 String elementName, String attributeName) { 123 124 // get elements that match 125 NodeList elements = document.getElementsByTagName(elementName); 126 127 // is there anything to do? 128 if (elements == null) { 129 return; 130 } 131 132 // print all elements 133 if (attributeName == null) { 134 int elementCount = elements.getLength(); 135 for (int i = 0; i < elementCount; i++) { 136 Element element = (Element)elements.item(i); 137 print(out, element, element.getAttributes()); 138 } 139 } 140 141 // print elements with given attribute name 142 else { 143 int elementCount = elements.getLength(); 144 for (int i = 0; i < elementCount; i++) { 145 Element element = (Element)elements.item(i); 146 NamedNodeMap attributes = element.getAttributes(); 147 if (attributes.getNamedItem(attributeName) != null) { 148 print(out, element, attributes); 149 } 150 } 151 } 152 153 } // print(PrintWriter,Document,String,String) 154 155 // 156 // Protected static methods 157 // 158 159 /** Prints the specified element. */ 160 protected static void print(PrintWriter out, 161 Element element, NamedNodeMap attributes) { 162 163 out.print('<'); 164 out.print(element.getNodeName()); 165 if (attributes != null) { 166 int attributeCount = attributes.getLength(); 167 for (int i = 0; i < attributeCount; i++) { 168 Attr attribute = (Attr)attributes.item(i); 169 out.print(' '); 170 out.print(attribute.getNodeName()); 171 out.print("=\""); 172 out.print(normalize(attribute.getNodeValue())); 173 out.print('"'); 174 } 175 } 176 out.println('>'); 177 out.flush(); 178 179 } // print(PrintWriter,Element,NamedNodeMap) 180 181 /** Normalizes the given string. */ 182 protected static String normalize(String s) { 183 StringBuffer str = new StringBuffer(); 184 185 int len = (s != null) ? s.length() : 0; 186 for (int i = 0; i < len; i++) { 187 char ch = s.charAt(i); 188 switch (ch) { 189 case '<': { 190 str.append("<"); 191 break; 192 } 193 case '>': { 194 str.append(">"); 195 break; 196 } 197 case '&': { 198 str.append("&"); 199 break; 200 } 201 case '"': { 202 str.append("""); 203 break; 204 } 205 case '\r': 206 case '\n': { 207 str.append("&#"); 208 str.append(Integer.toString(ch)); 209 str.append(';'); 210 break; 211 } 212 default: { 213 str.append(ch); 214 } 215 } 216 } 217 218 return str.toString(); 219 220 } // normalize(String):String 221 222 // 223 // MAIN 224 // 225 226 /** Main program entry point. */ 227 public static void main(String argv[]) { 228 229 // is there anything to do? 230 if (argv.length == 0) { 231 printUsage(); 232 System.exit(1); 233 } 234 235 // variables 236 PrintWriter out = new PrintWriter(System.out); 237 ParserWrapper parser = null; 238 String elementName = DEFAULT_ELEMENT_NAME; 239 String attributeName = null; 240 boolean namespaces = DEFAULT_NAMESPACES; 241 boolean validation = DEFAULT_VALIDATION; 242 boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; 243 boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; 244 boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; 245 boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; 246 boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; 247 boolean xincludeProcessing = DEFAULT_XINCLUDE; 248 boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; 249 boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; 250 251 // process arguments 252 for (int i = 0; i < argv.length; i++) { 253 String arg = argv[i]; 254 if (arg.startsWith("-")) { 255 String option = arg.substring(1); 256 if (option.equals("p")) { 257 // get parser name 258 if (++i == argv.length) { 259 System.err.println("error: Missing argument to -p option."); 260 } 261 String parserName = argv[i]; 262 263 // create parser 264 try { 265 parser = (ParserWrapper)Class.forName(parserName).newInstance(); 266 } 267 catch (Exception e) { 268 parser = null; 269 System.err.println("error: Unable to instantiate parser ("+parserName+")"); 270 } 271 continue; 272 } 273 if (option.equals("e")) { 274 if (++i == argv.length) { 275 System.err.println("error: Missing argument to -e option."); 276 } 277 elementName = argv[i]; 278 continue; 279 } 280 if (option.equals("a")) { 281 if (++i == argv.length) { 282 System.err.println("error: Missing argument to -a option."); 283 } 284 attributeName = argv[i]; 285 continue; 286 } 287 if (option.equalsIgnoreCase("n")) { 288 namespaces = option.equals("n"); 289 continue; 290 } 291 if (option.equalsIgnoreCase("v")) { 292 validation = option.equals("v"); 293 continue; 294 } 295 if (option.equalsIgnoreCase("s")) { 296 schemaValidation = option.equals("s"); 297 continue; 298 } 299 if (option.equalsIgnoreCase("f")) { 300 schemaFullChecking = option.equals("f"); 301 continue; 302 } 303 if (option.equalsIgnoreCase("hs")) { 304 honourAllSchemaLocations = option.equals("hs"); 305 continue; 306 } 307 if (option.equalsIgnoreCase("va")) { 308 validateAnnotations = option.equals("va"); 309 continue; 310 } 311 if (option.equalsIgnoreCase("dv")) { 312 dynamicValidation = option.equals("dv"); 313 continue; 314 } 315 if (option.equalsIgnoreCase("xi")) { 316 xincludeProcessing = option.equals("xi"); 317 continue; 318 } 319 if (option.equalsIgnoreCase("xb")) { 320 xincludeFixupBaseURIs = option.equals("xb"); 321 continue; 322 } 323 if (option.equalsIgnoreCase("xl")) { 324 xincludeFixupLanguage = option.equals("xl"); 325 continue; 326 } 327 if (option.equals("h")) { 328 printUsage(); 329 continue; 330 } 331 } 332 333 // use default parser? 334 if (parser == null) { 335 336 // create parser 337 try { 338 parser = (ParserWrapper)Class.forName(DEFAULT_PARSER_NAME).newInstance(); 339 } 340 catch (Exception e) { 341 System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")"); 342 continue; 343 } 344 } 345 346 // set parser features 347 try { 348 parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); 349 } 350 catch (SAXException e) { 351 System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")"); 352 } 353 try { 354 parser.setFeature(VALIDATION_FEATURE_ID, validation); 355 } 356 catch (SAXException e) { 357 System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")"); 358 } 359 try { 360 parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); 361 } 362 catch (SAXException e) { 363 System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")"); 364 } 365 try { 366 parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); 367 } 368 catch (SAXException e) { 369 System.err.println("warning: Parser does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); 370 } 371 try { 372 parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); 373 } 374 catch (SAXException e) { 375 System.err.println("warning: Parser does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); 376 } 377 try { 378 parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); 379 } 380 catch (SAXException e) { 381 System.err.println("warning: Parser does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); 382 } 383 try { 384 parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); 385 } 386 catch (SAXException e) { 387 System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")"); 388 } 389 try { 390 parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); 391 } 392 catch (SAXException e) { 393 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FEATURE_ID+")"); 394 } 395 try { 396 parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); 397 } 398 catch (SAXException e) { 399 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID+")"); 400 } 401 try { 402 parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); 403 } 404 catch (SAXException e) { 405 System.err.println("warning: Parser does not support feature ("+XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID+")"); 406 } 407 408 // parse file 409 try { 410 Document document = parser.parse(arg); 411 GetElementsByTagName.print(out, document, elementName, attributeName); 412 } 413 catch (SAXParseException e) { 414 // ignore 415 } 416 catch (Exception e) { 417 System.err.println("error: Parse error occurred - "+e.getMessage()); 418 if (e instanceof SAXException) { 419 Exception nested = ((SAXException)e).getException(); 420 if (nested != null) { 421 e = nested; 422 } 423 } 424 e.printStackTrace(System.err); 425 } 426 } 427 428 } // main(String[]) 429 430 // 431 // Private static methods 432 // 433 434 /** Prints the usage. */ 435 private static void printUsage() { 436 437 System.err.println("usage: java dom.GetElementsByTagName (options) uri ..."); 438 System.err.println(); 439 440 System.err.println("options:"); 441 System.err.println(" -p name Select parser by name."); 442 System.err.println(" -e name Specify element name for search."); 443 System.err.println(" -a name Specify attribute name for specified elements."); 444 System.err.println(" -n | -N Turn on/off namespace processing."); 445 System.err.println(" -v | -V Turn on/off validation."); 446 System.err.println(" -s | -S Turn on/off Schema validation support."); 447 System.err.println(" NOTE: Not supported by all parsers."); 448 System.err.println(" -f | -F Turn on/off Schema full checking."); 449 System.err.println(" NOTE: Requires use of -s and not supported by all parsers."); 450 System.err.println(" -hs | -HS Turn on/off honouring of all schema locations."); 451 System.err.println(" NOTE: Requires use of -s and not supported by all parsers."); 452 System.err.println(" -va | -VA Turn on/off validation of schema annotations."); 453 System.err.println(" NOTE: Requires use of -s and not supported by all parsers."); 454 System.err.println(" -dv | -DV Turn on/off dynamic validation."); 455 System.err.println(" NOTE: Not supported by all parsers."); 456 System.err.println(" -xi | -XI Turn on/off XInclude processing."); 457 System.err.println(" NOTE: Not supported by all parsers."); 458 System.err.println(" -xb | -XB Turn on/off base URI fixup during XInclude processing."); 459 System.err.println(" NOTE: Requires use of -xi and not supported by all parsers."); 460 System.err.println(" -xl | -XL Turn on/off language fixup during XInclude processing."); 461 System.err.println(" NOTE: Requires use of -xi and not supported by all parsers."); 462 System.err.println(" -h This help screen."); 463 System.err.println(); 464 465 System.err.println("defaults:"); 466 System.err.println(" Parser: "+DEFAULT_PARSER_NAME); 467 System.err.println(" Element: "+DEFAULT_ELEMENT_NAME); 468 System.err.print(" Namespaces: "); 469 System.err.println(DEFAULT_NAMESPACES ? "on" : "off"); 470 System.err.print(" Validation: "); 471 System.err.println(DEFAULT_VALIDATION ? "on" : "off"); 472 System.err.print(" Schema: "); 473 System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off"); 474 System.err.print(" Schema full checking: "); 475 System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off"); 476 System.err.print(" Honour all schema locations: "); 477 System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off"); 478 System.err.print(" Validate annotations: "); 479 System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off"); 480 System.err.print(" Dynamic: "); 481 System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off"); 482 System.err.print(" XInclude: "); 483 System.err.println(DEFAULT_XINCLUDE ? "on" : "off"); 484 System.err.print(" XInclude base URI fixup: "); 485 System.err.println(DEFAULT_XINCLUDE_FIXUP_BASE_URIS ? "on" : "off"); 486 System.err.print(" XInclude language fixup: "); 487 System.err.println(DEFAULT_XINCLUDE_FIXUP_LANGUAGE ? "on" : "off"); 488 489 } // printUsage() 490 491 } // class GetElementsByTagName