Remove Empty Lines from String or XML

To day I will show you How to Remove Empty Lines from string variable or  string Variable containing XML Data .

This Code will Work on Both C# and Java Language.

In Code I use Reg-ex Expression  To Detect or Find empty lines from String and Replace any other Character , join with Previous line or Else ..


Lets Start ;

String text = "line 1\n\nline 3\n\n\nline 5";
String adjusted = text.replaceAll("(?m)^[ \t]*\r?\n", "");

the String Variable adjusted Contain String Data With on empty Lines.
I Also Tested It with JavaScript and IT Works Fine.

You can use this small code when you are cleaning text or XML that comes from another system, for example generated files, copied content, or user input that contains extra blank lines. Removing the empty lines makes the output shorter, easier to read, and easier to compare in a diff tool.

Be careful with one case: sometimes a blank line has a meaning, for example between the paragraphs of a letter, or in a text file where empty lines separate sections. In that case do not remove all of them, or first keep a backup of the original text. A related cleanup task is removing empty XML tags, which I explained in my post about how to remove all empty tags from XML in Java and C#.

Comments