Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of an element in XML in Clojure?

Tags:

xml

clojure

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"
like image 615
yazz.com Avatar asked Jun 13 '11 09:06

yazz.com


3 Answers

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"
like image 199
user499049 Avatar answered Nov 20 '22 00:11

user499049


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"
like image 25
Jonas Avatar answered Nov 19 '22 23:11

Jonas


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]))
like image 6
Jürgen Hötzel Avatar answered Nov 20 '22 00:11

Jürgen Hötzel