Given a namespaced xml (ignored in this ex)
<foo>
<name>John</name>
<address>1 hacker way</address>
<phone></phone>
<school>
<name></name>
<state></state>
<type></type>
</school>
<college>
<name>mit</name>
<address></address>
<state></state>
</college>
</foo>
how would you write a function, remove-empty-tags with clojure.data.xml to return the following?
<foo>
<name>John</name>
<address>1 hacker way</address>
<college>
<name>mit</name>
</college>
</foo>
My solution so far is incomplete and looks like some recursion might help:
(require '[clojure.data.xml :as xml])
(defn- child-element? [e]
(let [content (:content e)]
(and (= (count content)
(count (filter #(instance? clojure.data.xml.node.Element %) content))))))
(defn remove-empty-tags
[xml-data]
(let [empty-tags? #(or (empty? %) (-> % .toString blank?))]
(reduce (fn [col e]
(if-not (empty-tags? (:content e))
(merge col e)
col)))
xml-data))
(def body (slurp "sample.xml")) ;; the above xml
(def xml-data (-> (xml/parse (java.io.StringReader. body)) :content))
(remove-empty-tags xml-data)
This returns, after converting to xml:
<foo>
<name>John</name>
<address>1 hacker way</address>
<school>
<name/>
<state/>
</school>
<college>
<name>mit</name>
<address/>
<state/>
</college>
</foo>
Clearly, this function needs to be recursive to remove empty child nodes using child-element?.
Suggestions?
xml-dataetc...