Pretty Print XML

Put this python file in your path to get the following:

#!/usr/bin/env python

"""
Command-line tool to validate and pretty-print XML.

Based on `pjson` but without the crap.

Usage::

    $ echo '<bunk atr="hello">world</bunk>' | pxml
	<?xml version="1.0" ?>
	<bunk atr="hello">
		world
	</bunk>

Original Author: Igor Guerrero <igfgt1@gmail.com>, 2012
Contributor: Matthew Gill, 2012
"""

import xml.dom.minidom
import sys

from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import XmlLexer

def format_xml_code(code):
    """
    Parses XML and formats it
    """
    x = xml.dom.minidom.parseString(code)
    return x.toprettyxml()

def color_yo_shit(code):
    """
    Calls pygments.highlight to color yo shit
    """
    return highlight(code, XmlLexer(), TerminalFormatter())

if __name__ == '__main__':
    code = format_xml_code(sys.stdin.read())
    print color_yo_shit(code)

The original can be found here (https://github.com/igorgue/pjson)

This entry was posted in uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published.