Here’s a little trick to format XML in BBEdit and vi.
BBEdit can format markup, but none of its built-in styles do what I want. Like so often when working with XML, the awesome libxml library helps out. It comes with the xmllint command line utility, which formats XML in a way I like.
In BBEdit, I use it as a UNIX Filter by storing the following script as xmllint.sh in the $HOME/Library/Application Support/BBEdit/Text Filters/xml directory.
#!/bin/sh XMLLINT_INDENT=$'\t' xmllint --format -
You can use spaces instead of a tab by changing \t.
It should show up in your UNIX Filters palette. Keep in mind that UNIX Filters in BBEdit operate on the selection or on the entire document if nothing is selected so you should make sure that there’s no selection.
The following version additionally performs some normalization (sort attribute order, unify attribute quotes etc.) by canonicalizing the output first.
#!/bin/sh xmllint --c14n - | XMLLINT_INDENT=$'\t' xmllint --format -
The vi editor also has a filter feature. To format using xmllint, type this sequence:
:%!xmllint --format -Or mark the area visually and then type
!xmllint --format -
The video shows these two:
Update May 2012: Adjusted the shell script snippets for BBEdit 10 and TextWrangler 4, which pass the text on STDIN instead of in a temp file. Also adjusted the location of text filter scripts inside BBEdit’s Application Support directory.
Brilliant, thanks for writing this up Marc. The first piece of code above works equally well in TextWrangler.
Great tip and a huge timesaver for me. tx!
I did this in TextWrangler, the only difference is that there is no xml subdir, you put it at the Unix Filters directory level and it appears in the Shebang->Unix Filters menu.
Same here--works great in TextWrangler. Thanks for this!
This doesn't seem to be working for me. I get the error message below:
warning: failed to load external entity ""
Any ideas?
Phil: Maybe try again with a simplified XML snippet to make sure you're doing it right and the required software is installed as required.
If that works but your own XML doesn’t, maybe you have stuff like DOCTYPEs with DTD references in there and it fails to load them. Try to remove the DOCTYPES, or adjust the DTD path / URL.
Dude this is freaking awesome. Thank you!
Thanks for your help, everyone.
When I run xmllint from the command line, it's clear that the problem is the encoding defined in my header:
<?xml version="1.0" encoding="MacRoman"?>
I wonder if there's a flag to have xmllint ignore the declared encoding?
Thanks this was just what I was looking for!
|



Great tip! I weren't aware of xmllint. And instructions for both my favourite editors - thanks :)