Search code examples
xmlclojurexml-generation

Simple Clojure XML edit


Let's say I have a vector of maps

[{:username "kbee" :firstname "Kay" :lastname "Bee"},
 {:username "jcee" :firstname "Jay" :lastname "Cee"}]

and i want to generate xml files for each map like the following

  <user>
   <username>kbee</username>
   <firstname>Kay</firstname>
   <lastname>Bee</lastname>
  </user>

how do i use just the clojure core library to achieve this. (I looked at enlive and fleet but they seemed a little complicated for me.)

ideally i'd like to do the following

(map #(spit (str (:username %) ".xml") (gen-xml sometemplate %) map-of-users))

Solution

  • Did you try clojure.xml/emit-element ? :

    (use 'clojure.xml)
    (def v [{:username "kbee" :firstname "Kay" :lastname "Bee"},
            {:username "jcee" :firstname "Jay" :lastname "Cee"}])
    
    (defn to-xml [m] (doseq [[k v] m] 
                      (emit-element {:tag k :content [v]}) ))
    

    Try out at REPL:

    user> (to-xml (first v))
    <username>kbee
    </username>
    <firstname>Kay
    </firstname>
    <lastname>Bee
    </lastname>
    nil
    

    All you need then is to wrap what's in the to-xml with a user tag.