Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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>
share|improve this question
    
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. –  B1KMusic Dec 13 '13 at 0:03
add comment

1 Answer

up vote 10 down vote accepted

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()
share|improve this answer
    
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
    
Ta! Da! It worked! Thank you! –  Rob Avery IV Jan 24 '13 at 20:22
    
Do you if you can set the tab indent size? For example: A parent's children will be 1 tab instead of 3 spaces, etc. –  Rob Avery IV Jan 25 '13 at 13:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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