liveBook · Manning

Clojure.xml

As explained in Clojure: The Essential Reference

clojure.xml is the Clojure namespace providing XML parsing and related XML input and output functionality.

clojure.xml provides XML parsing and emission for Clojure programs. Its main workflow turns an XML input source into an in-memory nested data structure for further processing, then converts that structure back to XML. section 22.0 section 22.1

The central operations have these contracts:

  • xml/parse accepts a java.io.File, a URL string, or a java.io.InputStream and returns nested structs and vectors. section 22.1
  • Each XML node contains :tag, :attrs, and :content; child elements and text appear in the :content vector. section 22.1
  • xml/emit accepts parsed XML data and writes its XML representation to standard output, returning nil. section 22.1
  • xml/parse accepts an optional startparse function for parser configuration, including disabling external schema loading or validation. section 22.1

Parse and emit a document

(require '[clojure.xml :as xml]) (def document (xml/parse "http://feeds.bbci.co.uk/news/rss.xml")) (keys document) ;; (:tag :attrs :content) (xml/emit {:tag :html :attrs {:xmlns "http://www.w3.org/1999/xhtml"} :content [{:tag :article :attrs nil :content ["Hello"]}]}) ;; <?xml version='1.0' encoding='UTF-8'?> ;; <html xmlns='http://www.w3.org/1999/xhtml'> ;; <article> ;; Hello ;; </article> ;; </html> ;; nil section 22.1

{:tag ...     ; #1
 :attrs ...
 :content
 [{:tag ... :attrs ... :content [...]}
  ...
  {:tag ...
   :attrs ...
   :content
   [{:tag ... :attrs ... :content [...]}
    ...
    {:tag ... :attrs ... :content [...]}]}]}

Inspect the recursive XML node shape before traversing or transforming parsed content. section 22.1

The namespace remains functional but has been proposed for deprecation and was not substantially redesigned; use Clojure Data XML whenever possible. section 22.1

How Clojure: The Essential Reference covers it

How deep it goes
Explains node representation, accepted inputs, emission behavior, and configurable validation, but defers broader XML processing.
Examples
Uses a BBC RSS URL, an XHTML document with an external DTD, a nested node map, and xml/emit output.
What it assumes
Assumes basic Clojure data structures and Java I/O awareness while introducing XML nodes as nested maps and vectors.
What you can do after
Apply it via xml/parse and xml/emit to load XML into memory, inspect its tree, and write XML output.
How it connects
Connects XML parsing with Clojure data structures, SAX parsers, XML validation, and Clojure Data XML.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.