Vim logo vim online Vim Book Ad

basic Tip #349: Format your xml document using xmllint

 tip karma   Rating 20/8, Viewed by 484 

created:   October 23, 2002 17:18      complexity:   basic
author:   Daniel Allen      as of Vim:   6.0

If you open an xml document that is either totally or partially unindented, you can use the GNU libxml2 libary's xmllint to reformat and align your document.  This is especially good if you want to save your xml documents using as little space as possible (which would be totally unindented).  Just add this under the autocmd section of your .vimrc file

au FileType xml exe ":silent 1,$!xmllint --format --recover - 2>/dev/null"

This instructs vim to take the entire contents of a *.xml file and pass it through xmllint, using the --format and --recover flags and silencing any errors that may occur.  This is generally a very effective process and will only mess up on very poorly typed (a large amout of incorrect syntax) xml documents.  Please note that xmllint only adds and removes structural space.  It does not remove space from regular text nodes (as doing so would be incorrect).

 rate this tip  Life Changing Helpful Unfulfilling 

<<Quickly insert a single word | when 'formatoptions' has o easily enter a non commented line: go/gO mappings >>

Additional Notes

Anonymous, October 24, 2002 14:11
will this work in win2k version of gvim?
[email protected], October 29, 2002 16:59
How can make it as a filter?

I tried sth like
  let&l;:equalprg='xmllint --format --recover'

but it didn't work since xmllint doesn't take STDIN?

any idea?
dean at mndsolutions dot de, November 8, 2002 9:47
notice the '-' given as the file argument to xmllint. This usually means stdin.
[email protected], November 14, 2002 13:13
Yes, xmllint can read from stdin, please note the '-' that occurs at the end of the options.  This tells it to dump the file contents to the stdin pipe for xmllint.  As far as I know, xmllint can be run in windows if you have gcc, but I am just projecting...look into it.  If not, I am sure you can find something to take its place...the tip is just that, a tip, build on it.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo