It is not clear why
XML string
without spaces cannot be generated in
C#
and it appears that the second block of code given in the question generates the
XML string without spaces
.
Further the Solution 1 given by
Collin Jasnoch can also be used to generate XML string without spaces.
However, if there is a
specific requirement
to remove spaces from the XML string, then
Replace
method of
Regex
class can be used to replace the spaces with
Empty string
as shown below:
string xmlString = @"< Root >< PC ID=1 / >< PC ID=12 / >< PC ID=25 / >< PC ID=29 / >< / Root >";
string xmlStringSansSpaces = Regex.Replace(xmlString,@"(?<=(?:<|/))\s+|\s+(?=(?:>))",
string.Empty, RegexOptions.CultureInvariant);
Console.WriteLine (xmlStringSansSpaces);
In the above code, the pattern
(?<=(?:<|/))\s+|\s+(?=(?:>))
searches for
whitespace
either preceded by
< or /
or followed by
>
but captures
only the whitespace
which is replaced with an
Empty
string.