Pretty print XML

This commit is contained in:
Justin Bonnar 2012-12-17 13:21:38 -08:00
parent 1766dd8291
commit 2e57c080fd

View File

@ -2,6 +2,7 @@
""" """
import json import json
import xml.dom.minidom
from functools import partial from functools import partial
from itertools import chain from itertools import chain
@ -20,6 +21,9 @@ from .input import (OUT_REQ_BODY, OUT_REQ_HEAD,
OUT_RESP_HEAD, OUT_RESP_BODY) OUT_RESP_HEAD, OUT_RESP_BODY)
# The default number of spaces to indent when pretty printing
DEFAULT_INDENT = 4
# Colors on Windows via colorama don't look that # Colors on Windows via colorama don't look that
# great and fruity seems to give the best result there. # great and fruity seems to give the best result there.
AVAILABLE_STYLES = set(STYLE_MAP.keys()) AVAILABLE_STYLES = set(STYLE_MAP.keys())
@ -385,13 +389,28 @@ class JSONProcessor(BaseProcessor):
content = json.dumps(json.loads(content), content = json.dumps(json.loads(content),
sort_keys=True, sort_keys=True,
ensure_ascii=False, ensure_ascii=False,
indent=4) indent=DEFAULT_INDENT)
except ValueError: except ValueError:
# Invalid JSON but we don't care. # Invalid JSON but we don't care.
pass pass
return content return content
class XMLProcessor(BaseProcessor):
"""XML body processor."""
def process_body(self, content, content_type, subtype):
if subtype == 'xml':
try:
# Pretty print the XML
doc = xml.dom.minidom.parseString(content)
content = doc.toprettyxml(indent=' '*DEFAULT_INDENT)
except xml.parsers.expat.ExpatError:
# Ignore invalid XML errors (skips attempting to pretty print)
pass
return content
class PygmentsProcessor(BaseProcessor): class PygmentsProcessor(BaseProcessor):
"""A processor that applies syntax-highlighting using Pygments """A processor that applies syntax-highlighting using Pygments
to the headers, and to the body as well if its content type is recognized. to the headers, and to the body as well if its content type is recognized.
@ -456,7 +475,8 @@ class OutputProcessor(object):
installed_processors = { installed_processors = {
'format': [ 'format': [
HeadersProcessor, HeadersProcessor,
JSONProcessor JSONProcessor,
XMLProcessor
], ],
'colors': [ 'colors': [
PygmentsProcessor PygmentsProcessor