Last active
December 27, 2021 14:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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