1 21 22 package nu.xom.samples; 23 24 import java.io.IOException ; 25 26 import nu.xom.Attribute; 27 import nu.xom.Builder; 28 import nu.xom.Document; 29 import nu.xom.NodeFactory; 30 import nu.xom.Nodes; 31 import nu.xom.ParsingException; 32 import nu.xom.Serializer; 33 34 55 public class NormalizingFactory extends NodeFactory { 56 57 private Nodes empty = new Nodes(); 58 59 public Nodes makeText(String data) { 61 data = normalizeSpace(data); 62 if ("".equals(data)) return empty; 63 return super.makeText(data); 64 } 65 66 public Nodes makeAttribute(String name, String URI, 67 String value, Attribute.Type type) { 68 value = normalizeSpace(value); 69 return super.makeAttribute(name, URI, value, type); 70 } 71 72 73 private static String normalizeSpace(String data) { 75 data = data.replace('\t', ' '); 76 data = data.replace('\n', ' '); 77 data = data.replace('\r', ' '); 78 data = data.trim(); 79 80 StringBuffer result = new StringBuffer (); 81 for (int i = 0; i < data.length(); i++) { 82 if (i == 0 || data.charAt(i-1) != ' ' 83 || data.charAt(i) != ' ') { 84 result.append(data.charAt(i)); 85 } 86 } 87 88 return result.toString(); 89 } 90 91 92 public static void main(String [] args) { 93 94 if (args.length == 0) { 95 System.out.println( 96 "Usage: java nu.xom.samples.NormalizingFactory URL" 97 ); 98 return; 99 } 100 101 Builder builder = new Builder(new NormalizingFactory()); 102 103 try { 104 Document doc = builder.build(args[0]); 105 Serializer serializer = new Serializer(System.out); 106 serializer.write(doc); 107 } 108 catch (ParsingException ex) { 110 System.out.println(args[0] + " is not well-formed."); 111 System.out.println(ex.getMessage()); 112 } 113 catch (IOException ex) { 114 System.out.println(ex); 115 } 116 117 } 118 119 } | Popular Tags |