Getting element value in XML in Clojure?

What is the easiest way to get element value from XML string in Clojure? I am looking for something like:

(get-value "<a><b>SOMETHING</b></a>)" "b") 

for return

 "SOMETHING" 
+7
source share
6 answers

Try the following:

 user=> (use 'clojure.xml) user=> (for [x (xml-seq (parse (java.io.File. file))) :when (= :b (:tag x))] (first (:content x))) 

See more details.

+5
source

Zippers can be convenient for xml, they give you xpath as a syntax that you can mix with clojure built-in 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 :bx/text) 

returns

 "SOMETHING" 
+10
source

I don’t know how idiomatic Clojure is, but if you know how to use XPath , it can be used quite easily in Clojure because of its excellent Java compatibility :

 (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" 
+7
source

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])) 
+6
source

This: Clojure XML Parsing is not what you want? An alternative (external) source is here: http://blog.rguha.net/?p=510 .

+2
source

Using clj-xpath, ( https://github.com/brehaut/necessary-evil ):

 (use 'com.github.kyleburton.clj-xpath :only [$x:text]) ($x:text "/a/b" "<a><b>SOMETHING</b></a>)") 
+2
source

All Articles