Emacs: How to Format an XML file

Using emacs in conjunction with libxml2 it is possible to quickly format an xml file into a more readable format. For the purposes of this example we will take the following xml file and reformat it. NB libxml2 must be installed on your machine

<?xml version="1.0"?>
<Tests xmlns="http://www.qedevelopment.co.uk">
  <Test Id="0001" Type="foo">
    <Name>Foo test</Name>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test Id="0002" Type="garp"><Name>Garp test</Name><Input>abc</Input><Output>def</Output></Test>
</Tests>

Enter the following command into emacs. Where C-x h represents the pressing of the <ctrl> key and the ‘x’ key at the same time followed by the ‘h’ key in order to select all the text in the buffer. M-| represents the pressing of the <esc> key followed by the ‘|’ key (not the simultaneous pressing of the two keys). The RET represents the return key, and don’t forget the ‘-‘ between it and the format.

C-x h C-u M-| xmllint --format - RET

You contents of the buffer should now have been reformatted as show below.

<?xml version="1.0"?>
<Tests xmlns="http://www.qedevelopment.co.uk">
  <Test Id="0001" Type="foo">
    <Name>Foo test</Name>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test Id="0002" Type="garp">
    <Name>Garp test</Name>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
</Tests>