What is the easiest way to get the value of an element from an XML string in Clojure? I am looking for something like:
(get-value "<a><b>SOMETHING</b></a>)" "b")
to return
"SOMETHING"
Zippers can be handy for xml, they give you xpath like syntax that you can mix with native clojure functions.
user=> (require '[clojure zip xml] '[clojure.contrib.zip-filter [xml :as x]])
user=> (def z (-> (.getBytes "<a><b>SOMETHING</b></a>")
java.io.ByteArrayInputStream.
clojure.xml/parse clojure.zip/xml-zip))
user=> (x/xml1-> z :b x/text)
returns
"SOMETHING"
I do not know how idiomatic Clojure it is but if you happen to know and like XPath it can be used quite easily in Clojure due to its excellent interoperability with Java:
(import javax.xml.parsers.DocumentBuilderFactory)
(import javax.xml.xpath.XPathFactory)
(defn document [filename]
(-> (DocumentBuilderFactory/newInstance)
.newDocumentBuilder
(.parse filename)))
(defn get-value [document xpath]
(-> (XPathFactory/newInstance)
.newXPath
(.compile xpath)
(.evaluate document)))
user=> (get-value (document "something.xml") "//a/b/text()")
"SOMETHING"
Using Christophe Grand's great Enlive library:
(require '[net.cgrand.enlive-html :as html])
(map html/text
(html/select (html/html-snippet "<a><b>SOMETHING</b></a>") [:a :b]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With