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>
About these ads

2 thoughts on “Formatting xml in emacs

  1. Bosstiger says:

    Reblogged this on Gigable – Tech Blog.

  2. Bosstiger says:

    Reblogged this on Gigable – Tech Blog.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,762 other followers

%d bloggers like this: