Eros
Eros

Reputation: 703

How to remove whitespace from an XmlDocument

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

Answers (3)

Ângelo Polotto
Ângelo Polotto

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

Oliver Turner
Oliver Turner

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

code-ninja
code-ninja

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

Related Questions