The
Replace
method of
Regex
class can be used to replace the
white space characters
with
_
as shown below
xmlText = Regex.Replace(
xmlText, @"(?=<[^=]+?>)(?=</?\w+\s+\w+)(<.*?)(\s+)(.*?>)",@"$1_$3",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
Where
xmlText
is the given xml text.
The search pattern
"(?=<[^=]+?>)(?=</?\w+\s+\w+)(<.*?)(\s+)(.*?>)"
searches white space between two words within
< and >
character where there is no
=
inside the
< and >
characters. However, the above replacement works to replace white spaces only at location between words.
i.e. if we have
<local unavailability local unavailability>
it will replace the first space between local and unavailability words.
<local_unavailability local unavailability>
If we ran the above second time with the replaced text then the second space will be replaced.
<local_unavailability_local unavailability>
The above pattern replaces multiple white spaces with a single
_
and also it replaces only between words. So, the spaces at the beginning and at end of words remain as it is.