Here is a quick pretty print function I wrote which requires no
additional libraries. This version takes a string and returns a
string. Since it parses the text before transforming it is probably
not the fastest but it worked fine for my needs when generating xml
and xhtml files. I hope someone finds this useful.
(import '(org.xml.sax InputSource)
'(java.io StringWriter StringReader)
'(javax.xml.parsers DocumentBuilder DocumentBuilderFactory)
'(javax.xml.transform Transformer TransformerFactory OutputKeys)
'(javax.xml.transform.dom DOMSource)
'(javax.xml.transform.stream StreamResult))
(defn pretty-print
"Attempts to pretty print a string. Any caught exceptions return the
original
string. Possible methods are 'xml', 'html' and 'text'. omit-xml-
declaration
is boolean. Indent-amount is hard-coded at 4 spaces in this version."
[method omit-xml-declaration text]
(try
(let [builder (.. DocumentBuilderFactory newInstance
newDocumentBuilder)
transformer (.. TransformerFactory newInstance newTransformer)
source (new InputSource (new StringReader text))
document (. builder parse source)
result (new StreamResult (new StringWriter))
]
(do
(. transformer setOutputProperty OutputKeys/INDENT "yes")
(. transformer setOutputProperty OutputKeys/METHOD method)
(if omit-xml-declaration
(. transformer setOutputProperty OutputKeys/OMIT_XML_DECLARATION
"yes"))
(. transformer setOutputProperty "{http://xml.apache.org/xslt}
indent-amount" "4")
(. transformer transform (new DOMSource document) result)
(.. result getWriter toString)))
(catch Exception _ text)))
-Tim
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---