Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added indentation support

  • Loading branch information...
commit d1228017b4416e361b68726856d46ee9f1e23f39 1 parent 47113a3
@senior senior authored
View
16 src/main/clojure/clojure/data/xml.clj
@@ -262,7 +262,21 @@
(.writeStartDocument writer (or (:encoding opts) "UTF-8") "1.0")
(emit-element e writer)
- (.writeEndDocument writer)))
+ (.writeEndDocument writer)
+ stream))
(defn emit [e & {:as opts}]
(apply emit-stream e *out* opts))
+
+(defn indenting-transformer []
+ (doto (-> (javax.xml.transform.TransformerFactory/newInstance) .newTransformer)
+ (.setOutputProperty (javax.xml.transform.OutputKeys/INDENT) "yes")
+ (.setOutputProperty (javax.xml.transform.OutputKeys/METHOD) "xml")
+ (.setOutputProperty "{http://xml.apache.org/xslt}indent-amount" "2")))
+
+(defn indent [e ^java.io.Writer stream & {:as opts}]
+ (let [sw (java.io.StringWriter.)
+ _ (apply emit-stream e sw opts)
+ source (-> sw .toString java.io.StringReader. javax.xml.transform.stream.StreamSource.)
+ result (javax.xml.transform.stream.StreamResult. stream)]
+ (.transform (indenting-transformer) source result)))
View
10 src/test/clojure/clojure/data/xml/test_emit.clj
@@ -81,4 +81,12 @@
(xml/emit (element :comment-stuff {}
"comment "
(xml-comment " goes here ")
- " not here"))))) )
+ " not here"))))) )
+
+(deftest test-indent
+ (let [nested-xml (lazy-parse* (str "<a><b><c><d>foo</d></c></b></a>"))
+ expect (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a>\n "
+ "<b>\n <c>\n <d>foo</d>\n </c>\n </b>\n</a>\n")
+ sw (java.io.StringWriter.)]
+ (xml/indent nested-xml sw)
+ (is (= expect (.toString sw)))))
Please sign in to comment.
Something went wrong with that request. Please try again.