Skip to content

Instantly share code, notes, and snippets.

@madstap
Last active December 27, 2021 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madstap/7ca22aa287e808c22bc2e9a3c2d9bdd3 to your computer and use it in GitHub Desktop.
Save madstap/7ca22aa287e808c22bc2e9a3c2d9bdd3 to your computer and use it in GitHub Desktop.
The stackoverflow answer to "how to pretty print xml in java" in clojure
(ns pretty-xml
(:import (java.io ByteArrayInputStream StringWriter)
(javax.xml.parsers DocumentBuilderFactory)
(javax.xml.transform TransformerFactory OutputKeys)
(javax.xml.transform.dom DOMSource)
(javax.xml.transform.stream StreamResult)
(javax.xml.xpath XPathFactory XPathConstants)
(org.w3c.dom Document NodeList Node)
(org.xml.sax InputSource))
(defn nodes-seq [^NodeList nodes]
(map #(.item nodes %) (range (.getLength nodes))))
;; https://stackoverflow.com/a/33541820/3680995
(defn pretty [^String s]
(let [input (-> s .getBytes ByteArrayInputStream. InputSource.)
doc (-> (DocumentBuilderFactory/newInstance)
.newDocumentBuilder
(.parse input)
(doto .normalize))
nodes (-> (XPathFactory/newInstance)
.newXPath
(.evaluate "//text()[normalize-space()='']"
doc
(XPathConstants/NODESET))
nodes-seq)
transformer
(doto (-> (TransformerFactory/newInstance) .newTransformer)
(.setOutputProperty OutputKeys/ENCODING "UTF-8")
(.setOutputProperty OutputKeys/INDENT "yes"))
stringwriter (StringWriter.)]
(run! #(doto (.getParentNode ^Node %) (.removeChild ^Node %)) nodes)
(.transform transformer (DOMSource. doc) (StreamResult. stringwriter))
(str stringwriter)))
(defn pprint [s]
(println (pretty s)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment