32

Is there an easy way within vi to make your XML text "pretty"?

For example:

I want this..

            <person>
  <name>Nick</name>
 <age>26</age>
         <gender>male</gender>
<occupation>doctor</occupation>
    </person>

to be this...

<person>
    <name>Nick</name>
    <age>26</age>
    <gender>male</gender>
    <occupation>doctor</occupation>
</person>
  • If all else fails, there's always macros. qq0dt<jq and then 3@qj@@5k4I<space><esc>j.j.j.. Wow, that looks pretty cryptic. – Braden Best Dec 13 '13 at 0:03
39

I've had the most luck with this:

:%!xmllint --format %

It's strict about your tags, though, so it will error out if your opening and closing tags don't match. It also adds an XML declaration at the top of your file, if you don't have one as well.

This page recommends the following, although I can't get it to work:

:set filetype=xml
:filetype indent on
gg=G

I tested it out, and it seems to work, somewhat. Not perfectly, but it gets the job done.

If that doesn't work well, you could use minidom in Python to format it for you.

import xml.dom.minidom

xml = xml.dom.minidom.parse(filename)
formatted_xml = xml.toprettyxml()
  • That gg=G command didn't really work. Instead, it just removed all the previous indentations I had. – Rob Avery IV Jan 24 '13 at 20:10
  • Yeah, I've found the same thing. It seems to work when I have a specific type of formatting already, but usually not. I'll have to test it out a bit more. – Nate Jan 24 '13 at 20:14
  • 1
    :%!xmllint --format % seems to work well, so I've added that to the post. – Nate Jan 24 '13 at 20:20
  • 1
    @kenny I modified the answer to cope with that – törzsmókus Aug 9 '17 at 15:10
  • 2
    I'm doing ":set ft=xml | %!xmllint --format -" to make it work on the current buffer and turn on syntax highlighting – grebulon Apr 26 '18 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.