Sometimes we need to clean up XML files before being able to make sense of them. Here is a quick way to get nicely formatted and readable XML files while using
xmllint is installed on your machine and it is in your path. It’s part of
The command above should display the manual for
xmllint if the program has been installed. Hit the
q key to exit.
Create a Custom Function
Add the following user defined command to your
function! DoCleanXML() " save the filetype so we can restore it later let l:origft = &ft set ft= " delete the xml header if it exists. This will " permit us to surround the document with fake tags " without creating invalid xml. 1s/<?xml .*?>//e " insert fake tags around the entire document. " This will permit us to pretty-format excerpts of " XML that may contain multiple top-level elements. 0put ='<CleanXML>' $put ='</CleanXML>' silent %!xmllint --format --encode utf-8 - " xmllint will insert an <?xml?> header setting its " encoding type to utf-8 " delete the fake tags 2d $d " restore the normal indentation silent %< " back to home 1 " restore the filetype exe "set ft=" . l:origft endfunction command! CleanXML call DoCleanXML()
Set the indent character by adding the following environment variable to your
.profile or similar file. In my case I inserted a tab between the double quotes.
export XMLLINT_INDENT=" "
Reload your environment
How to use it
Your custom command, CleanXML, is now available within your Vim editor. To use it, edit an XML file and type the following command to clean up its contents:
:CleanXML and hit enter.
This was adapted from a solution found on the Vim Tips Wiki