Reputation: 703
I have an XML document from which I want to remove white spaces and carriage returns. How can I get the modified XML using C#.
Upvotes: 10
Views: 34259
Reputation: 9531
I solved this just using a more complete regex:
var regex = new Regex(@"[\s]+(?![^><]*(?:>|<\/))");
var cleanedXml = regex.Replace(xml, "");
This regex will remove all the spaces between closed tags.
Input example:
<root>
<result success="1"/>
<userID>12345</userID>
<classID> 56543 </classID>
</root>
Output for the input:
<root><result success="1"/><userID>12345</userID><classID> 56543 </classID>
</root>
A more complete explanation of this regex can be found on this post: https://stackoverflow.com/a/25771445/6846888
Upvotes: 1
Reputation: 1392
Set the preserveWhitespace flag to false:
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load("foo.xml");
// doc.InnerXml contains no spaces or returns
Upvotes: 21
Reputation: 1626
To remove white spaces between the tags:
# Regex regex = new Regex(@">\s*<");
# string cleanedXml = regex.Replace(dirtyXml, "><");
Source and other usefull info here
Upvotes: 8