Formatting xml in emacs

I had this problem of debugging some xml but when reading the output of some log4j it was almost impossible to read so I needed some way of prettifying the xml quickly.

For this example I have the following xml:

<?xml version="1.0"?><xml><iq xmlns="jabber:component:accept" from="test1@temp.retep.org/client" id="iq_257" to="service.retep.org" type="get"><query xmlns="some:namespace"/></iq></xml>

So how do we pretify this in emacs?

Well the first thing to do is to write an extension function & place it into your ~/.emacs file. Placing it here means that when you open emacs the extension is available:

(defun xml-format ()
  (interactive)
  (save-excursion
    (shell-command-on-region (mark) (point) "xmllint --format -" (buffer-name) t)
  )
)

Now this works by passing the buffer to the xmllint utility and replaces it with the output – in this case nicely formatted xml.

Now we need to install xmllint:

pi@lindesfarne: ~$ sudo apt-get install libxml2-utils

Ok so now open emacs and open the xml. To format first select the xml you want to format then Press Escape then x followed by xml-format & press return. You should then get the xml nicely formatted:

<?xml version="1.0"?>
<xml>
  <iq xmlns="jabber:component:accept" from="test1@temp.retep.org/client" id="iq_257" to="service.retep.org" type="get">
    <query xmlns="some:namespace"/>
  </iq>
</xml>

Author: petermount1

Prolific Open Source developer who also works in the online gaming industry during the day. Develops in Java, Go, Python & any other language as necessary. Still develops on retro machines like BBC Micro & Amiga A1200

2 thoughts on “Formatting xml in emacs”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: