Clean up XML files in Vim

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 Vim.

Requirements

Make sure xmllint is installed on your machine and it is in your path. It’s part of libxml.

man xmllint

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 .vimrc file:

vim ~/.vimrc
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

source ~/.profile

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

This entry was posted in How-To, Tutorials and tagged , , , , on by .

About the author

Claude is an independent solutions architect at a renowned financial services firm. He also helps small businesses increase their productivity, improve back-office processes and reduce costs by promoting the use of new technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>