How can you filter text nodes in XML with Clojure zippers? For example, you may have a pretty-printed XML document that interleaves element nodes with text nodes containing whitespace:
(def doc
"<?xml version=\"1.0\"?>
<root>
<a>1</a>
<b>2</b>
</root>")
If you want to retrieve the content of the root's children, you can do this:
(require '[clojure.data.xml :as xml]
'[clojure.zip :as zip]
'[clojure.data.zip :as zf]
'[clojure.data.zip.xml :as zip-xml])
(-> doc
xml/parse-str
zip/xml-zip
(zip-xml/xml-> :root zf/children zip-xml/text))
However, this returns (" " "1" " " "2" " "), including the whitespace.
How do you filter the zipper, so that only element nodes are selected?
I've come up with this.
(def filter-elements (comp (partial filter (comp xml/element? zip/node)) zf/children))
(-> doc
xml/parse-str
zip/xml-zip
(zip-xml/xml-> :root filter-elements zip-xml/text))
; => ("1" "2")
I suspect it's unnecessarily complex and hence I'm looking for a better solution.