开发者

Getting the value of an element in XML in 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></开发者_C百科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]))


Try this:

user=> (use 'clojure.xml)

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

Check this link for more info.


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>)")


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜