Paul - The Programmer

simple & stupid

Auto format XML file

1. Format XML file with VIM.

VIM's auto indent feature supports format the XML files. But generally this feature may be disabled by default. 

To enable the auot indent feature, just add the below options in the .vimrc in user's home directory.

filetype indent on

Next time when the xml file be opened by VIM, the xml file type's indent script will be auotmatically loaded as well. In my environment, the indent script for xml is /usr/share/vim/vim72/ftplugin/xml.vim. The xml.vim's path may vary in different system.

To format the XML contents, just use the vim command in the command mode:

gg=G

This command will reformat the entire contents.

2. Fomart XML file with xmllint.

The xmllint are generally used for validating the xml file syntax. But it also has the ability to format and align the XML documents. The XMLLINT_INDENT environmnet variable controls the indentation. The default value is two spaces ( "  " ).

Basically, open the xml file with VIM then execute the below vim command in command mode:

 

:%!xmllint --format %

This command means the xmllint be excuted with the entire xml document contents as input, then the result of xmllint will be used to update the content of current buffer.

The xmllint also do some refine for the xml document, such as, adding the xml version declaration in the document's head.