Pretty Printing XML with Clojure

The other day, I did some XML cleanup. I am posting the snippet here for safekeeping purposes in case I need to refer to it later.

(defn ppxml [xml]
  (let [in (
            ( xml))
        writer (
        out ( writer)
        transformer (.newTransformer 
    (.setOutputProperty transformer 
                        javax.xml.transform.OutputKeys/INDENT "yes")
    (.setOutputProperty transformer 
                        "{}indent-amount" "2")
    (.setOutputProperty transformer 
                        javax.xml.transform.OutputKeys/METHOD "xml")
    (.transform transformer in out)
    (-> out .getWriter .toString)))

Now you can pass your XML string,

(ppxml "<root><child>aaa</child><child/></root>")

and get the pretty printed version,

<?xml version="1.0" encoding="UTF-8"?>

You can also use it to pretty print Compojure output either manually,

(ppxml (html
          [:title "Hello World"]]
         [:body "Hello World!"]]))

or using a middleware,

(defn with-ppxml [handler]
  (fn [request]
    (let [response (handler request)]
      (assoc response :body (ppxml (:body response))))))

and have your pretty printed HTML,

    <title>Hello World</title> 
  <body>Hello World!</body>