1 61 62 63 package org.jaxen.function; 64 65 import java.util.List ; 66 67 import org.jaxen.Context; 68 import org.jaxen.Function; 69 import org.jaxen.FunctionCallException; 70 import org.jaxen.Navigator; 71 72 93 public class NormalizeSpaceFunction implements Function 94 { 95 96 97 100 public NormalizeSpaceFunction() {} 101 102 117 public Object call(Context context, 118 List args) throws FunctionCallException 119 { 120 121 if (args.size() == 0) { 122 return evaluate( context.getNodeSet(), 123 context.getNavigator() ); 124 } 125 else if (args.size() == 1) 126 { 127 return evaluate( args.get(0), 128 context.getNavigator() ); 129 } 130 131 throw new FunctionCallException( "normalize-space() cannot have more than one argument" ); 132 } 133 134 147 public static String evaluate(Object strArg, 148 Navigator nav) 149 { 150 String str = StringFunction.evaluate( strArg, 151 nav ); 152 153 char[] buffer = str.toCharArray(); 154 int write = 0; 155 int lastWrite = 0; 156 boolean wroteOne = false; 157 int read = 0; 158 while (read < buffer.length) 159 { 160 if (isXMLSpace(buffer[read])) 161 { 162 if (wroteOne) 163 { 164 buffer[write++] = ' '; 165 } 166 do 167 { 168 read++; 169 } 170 while(read < buffer.length && isXMLSpace(buffer[read])); 171 } 172 else 173 { 174 buffer[write++] = buffer[read++]; 175 wroteOne = true; 176 lastWrite = write; 177 } 178 } 179 180 return new String (buffer, 0, lastWrite); 181 } 182 183 184 private static boolean isXMLSpace(char c) { 185 return c == ' ' || c == '\n' || c == '\r' || c == '\t'; 186 } 187 188 } 189 | Popular Tags |