Take the 2-minute tour ×

I have an html node:

ThereAreTwoSpacesAfterThis  ThereAreTwoSpacesBeforeThis

In any browser, the final use result is

Line1 Line2 Line ThereAreTwoSpacesAfterThis ThereAreTwoSpacesBeforeThis 

which is the result I want.

So how to remove the insignificant whitespace in a XmlNodeType.Text node (C#)?


Hi guys, Thanks for your reply.

Actually I'm working on a small project to extract all the text from a web page (html): something like "Save As page as text file" from Firefox or IE.

I tried to use Html Agility Pack, but the result is not good enough.

I also tried to use a WebBrowser control, but it seems too slow, and it's kind of not so easy to control over it.

Any good ideas?

I understand that guys suggest me to use regex, but there are too many cases to think about.

share|improve this question
Whoa, big fat shifting requirements. Your question was initially only about text inside a p tag and only about removing whitespace. Now you’re asking how to render an entire HTML page in plain-text?! Presumably you also want it to correctly interpret the CSS white-space property, which controls white-space collapsing, on every element? You’re on the first step to writing a fullblown HTML rendering engine. –  Timwi Sep 20 '10 at 3:05
You are right. Sorry for the confusion. I googled and searched a lot about converting html to plain text, but no luck. All I got is to use Html Agility Pack, which does not work enough for me. Thanks. –  Peter Lee Sep 25 '10 at 5:57
add comment

1 Answer

up vote 1 down vote accepted

Just use a regular expression!

var spacesSquashed = Regex.Replace(input, @"\s+", " ", RegexOptions.Singleline);

If you also want to remove all spaces at the beginning and end, as is customary in HTML, add an extra .Trim() at the end.

share|improve this answer
Tempted to upvote because you included that quote :) For this specific usage I guess regex is okay... –  Alex Paven Sep 13 '10 at 8:21
Please see my updated question. Thanks for your reply. –  Peter Lee Sep 19 '10 at 21:04
add comment

Your Answer


