views:

29

answers:

3

So there's a messy XML file where all white spaces between tags have been stripped, so it's a valid XML file but it's somewhat unreadable.

I press the magic Ctrl+K, D, and the file is beautifully formatted.

I edit it, and then I want to put it back into the compressed, hardly readable state, removing all whitespaces between the tags. How do I do that in VS 2008? I looked though the list of all available commands but couldn't find any.

A: 

The only thing I can think of is to select all the file and then keep pressing Shift+Tab until you've removed all the tabs. It won't remove all the white space though, just that at the beginning of each line.

ChrisF
A: 

I don't think you can come back to the original formatting if you made edits. What I would do is use emacs macros: you can do a set of keys for one line and repeat it for the whole file:

C-x ( start recording key strokes to build a keyboard macro.

C-x ) stop recording key strokes to for a keyboard macro.

then the following instruction will repeat it 200 times:

C-u 200 C-x e

(I know Visual Studio and emacs are different worlds but in some situations emacs and cygwin are the only way to go really)

Bob Yoplait
+2  A: 

Using Notepad++

I recommend you get Notepad++ and install the XML Tools plugin. The Plugins > XML Tools menu contains a Linarize XML item that does exactly what you want.

Using Visual Studio

You could do a Find & Replace using a regular expression.

First remove all the whitespace preceding any XML tags using these search criteria:

Find what: :Wh*[<]
Replace with: <

Then remove all the whitespace preceding any text or attributes:

Find what: :Wh+{:Al}
Replace with: \1

Note: There should be a space in front of \1.

Disclaimer: This method may not be completely accurate, so make sure to double-check the result!

Niels van der Rest
You beat me to it, +1 for the recommendation of Notepad++... seems like your answer is more complete than the one I was about to post anyway! 8-)
Richard
The regexp will hardly work, given the contents of CDATA sections, but I like your answer most.
GSerg