Formatting/Validating XML while you type...

When you edit some XML it happens a lot of times that you just think about the tags you need or you want to check, if the file is correct by validating it. BUT using an extra tool for that is maybe not the best way because it takes quite some time. So why don't you just tell your editor to validate or format the file you are currently editing ?! This little tip can show you how easy this can be done and it works of course with any other command line based program just the same way. VIM almighty...

First thing to have of course is the VIM editor and xmllint installed (under Unix-like systems this should be standard). You can find everything you need at xmlsoft . 

To start it is useful to beautify your XML, which can be done with this command in VIM

:%!xmllint --format -

The beginning % tells vim to apply the following command to the whole file that is currently open. xmllint --format will beautify your XML and the  - at the end will paste the file to the standard input of the program. The ! will take care of pasting the output back into the current swap. And your are done with that. Users with any other character encoding than UTF-8 might just use this line instead

:%!xmllint --format --encode UTF-8 -

If you just want to check whether your file is well formed, you can simply use this line

:!xmllint --noout %
which will check the whole file but won't create an output.

Finally just this line that will help you to validate your file with a given DTD

:%w !xmllint --noout --dtdvalid /path/to/your.dtd -

Anything else you need to know can be found at pinkjuice where I also got the tips from.

Author: Frederic Siepmann, published: 2007-07-18 11:47:12