Stefano Locati

Programming Adventures (WIP)

Formatting XML

Often I would like to reformat XML, so that is properly indented. It's important that a tool does this, because if done manually is prone to mistakes. Automatic reformat makes it easier to find issues, and in any case it will make the file more readable.

If I'm inside Eclipse, I just open the file and press CTRL + SHIFT + f and the file is reformatted (works with XML and source code).

Instead, from the command line, it's possible to use xmllint, for example to reformat a pom.xml file:

[sourcecode language="bash"]

xmllint --format pom.xml --output pom.xml


However, the default is only 2 spaces, which might be OK for some, but for me is definitely not enough. To change this default, you've to use XMLLINT_INDENT variable. This variable has to be set with whatever you want to use to indent one level, such as 4 or 8 spaces.

[sourcecode language="bash"]

export XMLLINT_INDENT=" ";


If you type the above command in the shell, in the next session, it will be forgotten, to make it persist, there are several ways, but for my environment variables I've a .bash_local file in my home directory, in which I've also the line above.

In .bashrc I've added a call to .bash_local.

[sourcecode language="bash"]

. ~/.bash_local


The reason why I don't modify directly .bashrc, is that so I can see my modifications easily and make it easier to move to a new PC (which can happen as often as every 6/12 months in my case).

In Emacs C-x h selects the entire buffer, and C-M-\ formats it. (The Meta key is Alt on PC Linux keyboards).