@@ -268,22 +268,114 @@ internal static string GetText(XmlTextSyntax textElement, bool normalizeWhitespa
268268 return null ;
269269 }
270270
271- StringBuilder stringBuilder = StringBuilderPool . Allocate ( ) ;
271+ string result = string . Empty ;
272+
273+ StringBuilder stringBuilder = null ;
272274
273275 foreach ( var item in textElement . TextTokens )
274276 {
275- stringBuilder . Append ( item ) ;
277+ if ( result . Length == 0 )
278+ {
279+ result = item . ToString ( ) ;
280+ }
281+ else
282+ {
283+ if ( stringBuilder == null )
284+ {
285+ stringBuilder = StringBuilderPool . Allocate ( ) ;
286+ stringBuilder . Append ( result ) ;
287+ }
288+
289+ stringBuilder . Append ( item . ToString ( ) ) ;
290+ }
291+ }
292+
293+ if ( stringBuilder != null )
294+ {
295+ result = StringBuilderPool . ReturnAndFree ( stringBuilder ) ;
276296 }
277297
278- string result = StringBuilderPool . ReturnAndFree ( stringBuilder ) ;
279298 if ( normalizeWhitespace )
280299 {
281- result = Regex . Replace ( result , @"\s+" , " " ) ;
300+ result = result . NormalizeWhiteSpace ( ) ;
282301 }
283302
284303 return result ;
285304 }
286305
306+ internal static string NormalizeWhiteSpace ( this string text )
307+ {
308+ if ( text == null )
309+ {
310+ return null ;
311+ }
312+
313+ int length = text . Length ;
314+
315+ if ( length == 0 )
316+ {
317+ return string . Empty ;
318+ }
319+
320+ bool lastSpace = false ;
321+
322+ bool diff = true ;
323+
324+ foreach ( char ch in text )
325+ {
326+ if ( char . IsWhiteSpace ( ch ) )
327+ {
328+ if ( lastSpace )
329+ {
330+ length -- ;
331+ }
332+ else
333+ {
334+ if ( ch != ' ' )
335+ {
336+ diff = true ;
337+ }
338+
339+ lastSpace = true ;
340+ }
341+ }
342+ else
343+ {
344+ lastSpace = false ;
345+ }
346+ }
347+
348+ if ( diff || ( length != text . Length ) )
349+ {
350+ char [ ] buffer = new char [ length ] ;
351+
352+ lastSpace = false ;
353+
354+ length = 0 ;
355+
356+ foreach ( char ch in text )
357+ {
358+ if ( char . IsWhiteSpace ( ch ) )
359+ {
360+ if ( ! lastSpace )
361+ {
362+ buffer [ length ++ ] = ' ' ;
363+ lastSpace = true ;
364+ }
365+ }
366+ else
367+ {
368+ buffer [ length ++ ] = ch ;
369+ lastSpace = false ;
370+ }
371+ }
372+
373+ return new string ( buffer , 0 , length ) ;
374+ }
375+
376+ return text ;
377+ }
378+
287379 internal static T GetFirstAttributeOrDefault < T > ( XmlNodeSyntax nodeSyntax )
288380 where T : XmlAttributeSyntax
289381 {
0 commit comments