Working with XML

How to:

Clojure offers the library for XML parsing and emitting. First, let’s parse some XML:

(require '[ :as xml])

(let [content "<root><foo>bar</foo><foo>baz</foo></root>"
      parsed (xml/parse-str content)] ; Parse XML string
  (println parsed))


Element{:tag :root, :attrs {}, :content (Element{:tag :foo, :attrs {}, :content ("bar")} Element{:tag :foo, :attrs {}, :content ("baz")})}

To emit XML from Clojure structures:

(def my-xml (xml/element :root {}
                          (xml/element :foo {} "bar")
                          (xml/element :foo {} "baz")))

(println (xml/emit-str my-xml))



Deep Dive

XML’s been around the block, kicking off in the late ’90s as a simplified subset of SGML, intended for web data. It exploded in usage with technologies like SOAP and XHTML but got a bit of competition from JSON, which is preferred for its lightness and simplicity.

Clojure’s approach to XML keeps it functional and data-centric, staying true to the language ethos. is merely one option; you’ve got clojure.xml for basic needs, and for Java interop, you can swing with heavy-hitters like JAXB or DOM4J.

Keep in mind, the performance and memory overhead when dealing with very large XML documents can be hefty. Streaming parsers like StAX can help, but you’ll need to drop into Java-land for them.

See Also