Saturday, 7 June 2008

How do I remove whitespace from XML in C#.NET?

Once again... thanks Neil!

using System;
using System.Text.RegularExpressions;

public static class XMLUtility
{
public static string RemoveWhitespace( string xml )
{
Regex regex = new Regex(@">\s*<");
xml = regex.Replace(xml, "><");

return xml.Trim();
}
}

3 comments:

Mukesh Giri said...

Hi :
How can i use your code for my case ?
private void saveDocument(XmlDocument doc, string filename)
{
StreamWriter wr = new StreamWriter(filename);
wr.Write(doc.OuterXml);
wr.Close();
wr.Dispose(); }

I get white space in my xml output after i compile my project???

Andrew Gunn said...

Try removing the XML whitespace from doc.OuterXml when you write it into the StreamWriter:

wr.Write(XMLUtility.RemoveWhitespace(doc.OuterXml));

Check out CodeContrib for more examples and extra helpers.

Anonymous said...

This saved my life !!
Thanks Andrew !!!!!!!!